python - 带有 If Else 语句的 Python Tkinter 按钮
问题描述
我想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?
有谁知道something
,应something_else
该做什么if-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()
推荐阅读
- mysql - Ubuntu 的 MySQL 工作台中没有模式面板
- mongodb - 创建具有交替 IP 地址的服务器副本集
- php - 错误的 php 和 XML 声明只允许在文档的开头
- typescript - 打字稿反应道具验证不起作用
- reactjs - Employee.map 不是函数
- c# - 是否可以指示 C# 编译器不要内联常量?
- reactjs - 尽管我添加了链接标签,但无法重定向到 ReactJS 中的错误页面
- python - mysql.connector.errors.IntegrityError: 1062 (23000): 键 'PRIMARY' 的重复条目 '3'
- c# - 如何拆分后缀表达式以便我们可以并行评估它们?
- python - Google Auth 无法在 Heroku 上为烧瓶/反应应用程序工作