【发布时间】: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.")
有没有办法让.bind 和command 共享相同的功能?
【问题讨论】:
标签: python tkinter bind tkinter-entry