'Python Tkinter Button with If Else statements
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?
Solution 1:[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()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Artemis |
