【问题标题】:Python Tkinter one callback function for two buttonsPython Tkinter 两个按钮的一个回调函数
【发布时间】:2013-04-13 09:53:12
【问题描述】:

我一直在四处寻找这个问题的答案,但仍然没有找到任何答案。我正在使用 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()

【问题讨论】:

  • 这并没有真正回答您的问题,但您可以做的是创建三个函数:一个仅在您单击按钮 1 时获取值,另一个函数仅在您单击时获取值按钮 2,以及包含 200 行函数的第三个函数。然后,前两个函数可以只调用第三个函数并传入值,这样您就不需要 if 语句将事情搞得一团糟。

标签: python button callback tkinter


【解决方案1】:

如果你想将实际的小部件传递给回调,你可以这样做:

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):
    ...

还有其他方法可以解决同样的问题,但希望这能让您大致了解如何将值传递给按钮回调,或者如何避免一开始就需要这样做。

【讨论】:

  • 非常感谢布莱恩!我认为我的逻辑完全错误,这真的很有帮助。
猜你喜欢
  • 1970-01-01
  • 2022-12-13
  • 2013-04-11
  • 1970-01-01
  • 1970-01-01
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
  • 2014-01-10
相关资源
最近更新 更多