带有If Else语句的Python Tkinter按钮 [英] Python Tkinter Button with If Else statements

查看:225
本文介绍了带有If Else语句的Python Tkinter按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将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?

有人知道somethingsomething_elseif-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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆