我如何使Bind和Command在tkinter中执行相同的操作? [英] How do I make Bind and Command do the same thing in tkinter?
问题描述
我有一个带有输入字段和验证按钮的tkinter GUI.当我按条目中的一个键或单击按钮时,我想调用相同的功能.
I have a tkinter GUI with an entry field and a validation button. I'd like to call the same function when I press a key in the entry, or when I click the button.
问题是,使用条目上的bind方法,我需要一个"self"参数来使函数正常工作,而不是使用按钮.
The problem is, with the bind method on the entry, I need a "self" argument for my function to work, but not with the button.
这是简化的代码:
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()
使用此代码,当我使用按钮时,没问题,它会打印,但是当我使用绑定时,它会返回:
With this code, when I use the button, no problem, it prints, but when I use the bind, it returns:
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
我可以通过调用两个函数来使其工作,其中一个函数用于按钮,另一个函数用于带有自变量的条目:
I can make it work by calling two functions one for the button, and another for the entry with a self argument:
def function2(self):
print("It works with this function.")
有什么办法可以使.bind
和command
共享相同的功能?
Is there any way to make both .bind
and command
share the the same function?
推荐答案
将此添加到您的绑定中:
Add this to your binding:
input_widget.bind("<Return>", lambda event: function())
事件绑定都需要一个事件参数,该参数将自动传递给函数.通过将lambda与参数event配合使用;您可以使用此事件"变量,基本上将其丢弃,然后执行function()
Event bindings all require an event parameter which is automatically passed to the function. By using a lambda with the parameter event; you can take in this "event" variable and basically discard it and do whatever is in function()
这篇关于我如何使Bind和Command在tkinter中执行相同的操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!