Python Tkinter一个用于两个按钮的回调函数


问题内容

我一直在寻找这个问题的答案很长时间了,但仍然没有找到任何东西。我正在使用Tkinter创建GUI,并且我有两个按钮执行的功能大致相同,只是它们从不同的小部件接收信息。一个按钮用于Entry小部件,另一个按钮用于Listbox小部件。这两个按钮的回调函数很长(大约200行),因此我不想为每个按钮都设置单独的函数。我在此回调函数的开头有if语句,以检查单击了哪个按钮,然后代码将采用相应的值。但是我不确定下面的代码是否显示正确的方法,因为显然它在我的程序中无法完美运行。回调函数只能在第一次使用,如果我单击其他按钮,将会收到错误消息。这是我创建的示例代码,用于说明该想法。请注意,我想检查按钮是否被单击,我不想检查“值”是否存在。请帮忙。

from Tkinter import *

root = Tk()

def DoSomething():
    # is this the right way to check which button is clicked?
    if button1:
        value = user_input.get()
    elif button2:
        value = choice.get(choice.curselection()[0])

    # then more codes that take 'value' as input.


button1 = Button(master,text='Search',command=DoSomething)
button1.pack()
button2 = Button(master,text='Search',command=DoSomething)
button2.pack()

user_input = Entry(master)
user_input.pack()
choice = Listbox(master,selectmode=SINGLE)
choice.pack()
#assume there are items in the listbox, I skipped this portion

root.mainloop()

问题答案:

如果要将实际的小部件传递到回调中,可以这样进行:

button1 = Button(master, text='Search')
button1.configure(command=lambda widget=button1: DoSomething(widget))
button2 = Button(master, text='Search')
button2.configure(command=lambda widget=button2: DoSomething(widget))

另一个选择是,如果您确实不需要引用小部件,则只需传递文字字符串:

button1 = Button(..., command=lambda widget="button1": DoSomething(widget))
button2 = Button(..., command=lambda widget="button2": DoSomething(widget))

另一个选择是给每个按钮一个唯一的回调,并使该回调仅执行该按钮唯一的操作:

button1 = Button(..., command=ButtonOneCallback)
button2 = Button(..., command=ButtonTwoCallback)

def ButtonOneCallback():
    value = user_input.get()
    DoSomething(value)

def ButtonTwoCallback():
    value=choice.get(choice.curselection()[0])
    DoSomething(value)

def DoSomething(value):
    ...

还有其他方法可以解决相同的问题,但是希望这可以使您大致了解如何将值传递给按钮回调,或者首先可以避免这样做。