带有If Else语句的Python Tkinter按钮 [英] Python Tkinter Button with If Else statements
问题描述
我想将Start_Button
绑定到2种可能的功能:
I want to bind the Start_Button
with 2 possible functions:
如果先单击Choice_1_Button
,然后单击Start_Button
,则Start_Button
应调用foo1
.但是,当用户单击Choice_2_Button
时,相同的Start Button
应该调用foo2
.
If Choice_1_Button
is clicked and then the Start_Button
, the Start_Button
should call foo1
. But when the user clicks Choice_2_Button
then the same Start Button
should call foo2
.
这是我当前拥有的代码:
Here is the code I currently have:
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?
有人知道something
,something_else
和if-something
应该做什么吗?
Does anyone know what something
, something_else
and if-something
should do?
推荐答案
以下代码跟踪其按下的内容:
The following code keeps track of what they pressed:
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
的命令.
Pass choice1
as the command for Choice_1_Button
, choice2
as the command for Choice_2_Button
, and start
for Start_Button
.
如果要使用单选按钮,将使其变得更容易:
If you want to use radio buttons, it will make it easier:
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()
这篇关于带有If Else语句的Python Tkinter按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!