如何根据 tkinter 的下拉菜单结果使同一个按钮执行不同的操作?

How to make same button do different actions depending on dropdown menu result with tkinter?

有没有办法让同一个按钮根据用户从下拉菜单中选择的内容执行不同的操作?

例如,我试过这个,但它不起作用:

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

您需要 link 您的按钮到一个函数,并在该函数中包含您的 if 语句。然后像这样使用您的函数作为按钮的命令。

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