'How to make same button do different actions depending on dropdown menu result with tkinter?
is there a way to make the same button do different actions depending on what the user chooses from drop down menu?
I tried this for example, but it doesn't work:
from tkinter import *
from tkinter import ttk
root = Tk()
root.geometry("400x200")
def say_hello():
hello_label = Label(root, text= "Hello")
hello_label.grid(row=1, column=0, padx=10, pady=10)
def say_goodbye():
bye_label = Label(root, text= "Goodbye")
bye_label.grid(row=1, column=0, padx=10, pady=10)
do = ""
drop_table = ttk.Combobox(root, values=["Choose Action..", "Say Hello","Say Goodbye"])
drop_table.current(0)
drop_table.grid(row=0, column=0, padx=10, pady=10)
selected = drop_table.get()
if selected == "Say Hello":
do = say_hello
if selected == "Say Goodbye":
do = say_goodbye
button = Button(root, text= "Choose", command = do)
button.grid(row=0, column=2, padx=10, pady=10)
root.mainloop()
Solution 1:[1]
You would need to link your button to a function and include your if statements in the function. Then use your function as the command for your button like this.
from tkinter import *
from tkinter import ttk
root = Tk()
root.geometry("400x200")
def say_hello():
hello_label = Label(root, text= "Hello")
hello_label.grid(row=1, column=0, padx=10, pady=10)
def say_goodbye():
bye_label = Label(root, text= "Goodbye")
bye_label.grid(row=1, column=0, padx=10, pady=10)
do = ""
drop_table = ttk.Combobox(root, values=["Choose Action..", "Say Hello","Say Goodbye"])
drop_table.current(0)
drop_table.grid(row=0, column=0, padx=10, pady=10)
def action():
selected = drop_table.get()
if selected == "Say Hello":
say_hello()
if selected == "Say Goodbye":
say_goodbye()
button = Button(root, text= "Choose", command= action)
button.grid(row=0, column=2, padx=10, pady=10)
root.mainloop()
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 | Rory |
