Python Tkinter Button with If Else statements



我想用 2 个可能的函数绑定Start_Button

如果单击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应该做什么?

以下代码跟踪他们按下的内容:

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_Button的命令,choice2作为Choice_2_Button的命令,start作为Start_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()

最新更新