【问题标题】:How do I make Bind and Command do the same thing in tkinter?如何让 Bind 和 Command 在 tkinter 中做同样的事情?
【发布时间】:2015-06-17 12:39:15
【问题描述】:

我有一个带有输入字段和验证按钮的 tkinter GUI。当我在条目中按下一个键或单击按钮时,我想调用相同的函数。

问题是,使用条目上的绑定方法,我需要一个“自我”参数才能使我的函数工作,但不需要按钮。

这里是简化的代码:

from tkinter import *
import tkinter.messagebox
import tkinter.filedialog


def function():
    print("Here are some words.")

my_window = Tk()

text = StringVar()
input_widget = Entry(my_window, textvariable = text) #We create an input widget.
input_widget.bind("<Return>", function)

benjamin = Button(my_window, text ='Print', command = function) #We create another widget, a 
# button that sends the same function as pressing <Return> key.

input_widget.grid(row = 0, column = 0) #We use grid to place our widgets.
benjamin.grid(row = 0, column = 1)


my_window.mainloop()

使用此代码,当我使用按钮时,没问题,它会打印,但是当我使用绑定时,它会返回:

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\"blablabla"\tkinter\__init__.py, line 1533, in __call__
    return self.func(*args)
TypeError: function() takes 0 positionnal arguments but 1 was given

我可以通过调用两个函数来使其工作,一个用于按钮,另一个用于带有 self 参数的条目:

def function2(self):
    print("It works with this function.")

有没有办法让.bindcommand 共享相同的功能?

【问题讨论】:

    标签: python tkinter bind tkinter-entry


    【解决方案1】:

    你可以编写你的函数,让它接受任意数量的参数:

    def function(*args):
        #args is now a tuple containing every argument sent to this function
        print("Here are some words.")
    

    现在您可以使用 0、1 或任何其他数量的参数成功调用函数。


    或者,您可以保持函数不变,并使用 lambda 丢弃未使用的 self 值:

    input_widget.bind("<Return>", lambda x: function())
    

    【讨论】:

    • 问题越长,答案越短。感谢您以如此快速有效的方式回答!为我工作。
    • 第一个解决方案很好,但是,问题在于传递的事件,而不是自身;没有使用任何类。 self 不是调用你的函数的“必要”,它只是接受从绑定传递的“事件”。
    【解决方案2】:

    将此添加到您的绑定中:

    input_widget.bind("<Return>", lambda event: function())
    

    事件绑定都需要一个自动传递给函数的事件参数。通过使用带有参数 event 的 lambda;您可以接受这个“事件”变量并基本上丢弃它并执行function()中的任何操作

    【讨论】:

      猜你喜欢
      • 2013-07-19
      • 1970-01-01
      • 1970-01-01
      • 2016-03-17
      • 2018-05-18
      • 2020-10-28
      • 2021-05-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多