[英]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()
You would need to link your button to a function and include your if statements in the function.您需要将按钮链接到函数并将 if 语句包含在函数中。 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.