Python Tkinter Button with If Else statements

泪湿孤枕 提交于 2020-01-06 04:42:43

问题


I want to bind the Start_Button with 2 possible functions:

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?

Does anyone know what something, something_else and if-something should do?


回答1:


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

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()


来源:https://stackoverflow.com/questions/50050440/python-tkinter-button-with-if-else-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!