【问题标题】:Python Tkinter Button with If Else statements带有 If Else 语句的 Python Tkinter 按钮
【发布时间】:2018-10-07 14:14:12
【问题描述】:

我想将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 应该做什么吗?

【问题讨论】:

  • 只调用一个函数。在该函数中,使用 var.get 查询您的 Radiobuttons 变量并调用适当的函数(func1()func2())。

标签: python if-statement button tkinter


【解决方案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_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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-02
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-03
    • 1970-01-01
    相关资源
    最近更新 更多