Python的Tkinter的按键采用的if else语句(Python Tkinter Butto

2019-10-30 02:45发布

我想将绑定Start_Button有2个可选功能:

如果Choice_1_Button点击,然后Start_Button ,该Start_Button应该调用foo1 。 但是,当用户点击Choice_2_Button那么同样的Start Button应该叫foo2

这是我目前拥有的代码:

from tkinter import *
root=Tk()
Choice_1_Button=Button(root, text='Choice 1', command=something) #what should it do?
Choice_2_Button=Button(root, text='Choice 2', command=something_else)
Start_Button=Button(root, text='Start', command=if_something) #and what about this?

有谁知道是什么somethingsomething_elseif-something应该怎么办?

Answer 1:

下面的代码跟踪他们按下了什么:

choice=None
def choice1():
    global choice
    choice='Choice 1'
def choice2():
    global choice
    choice='Choice 2'
def start():
    global choice
    if choice=='Choice 1':
        foo1()
    elif choice=='Choice 2':
        foo2()
    else:
        #do something else since they didn't press either

通过choice1作为命令Choice_1_Buttonchoice2作为命令Choice_2_Button ,并startStart_Button

如果你想使用单选按钮,它会更容易:

def start(choice):
    if choice=='Choice 1':
        foo1()
    elif choice=='Choice 2':
        foo2()
    else:
        #do something else since they didn't press either
var=StringVar(root)
var.set(None)
Radiobutton(root, text='Choice 1', value='Choice 1', variable=var).pack()
Radiobutton(root, text='Choice 2', value='Choice 2', variable=var).pack()
Button(self.frame, text='Start', command=lambda: start(var.get())).pack()


文章来源: Python Tkinter Button with If Else statements