类内Tkinter事件处理器遇到问题
我的问题是,我有一个类,这个类创建了一个Tkinter的顶层窗口对象,然后在里面放了一个字段。我想添加一个事件处理器,让它在每次按下按钮时运行一个方法(这个方法也在这个类里面)。但是当事件被触发时,它显示了
AttributeError: Toplevel实例没有'updateSearch'这个属性
class EditStudentWindow():
def __init__(self):
searchResultList = ['student1', 'student2', 'student3'] # test list
##### window attributes
# create window
self = Tkinter.Toplevel()
#window title
self.title('Edit Students')
##### puts stuff into the window
# text
editStudentInfoLabel = Tkinter.Label(self,text='Select the student from the list below or search for one in the search box provided')
editStudentInfoLabel.grid(row=0, column=0)
# entry box
searchRepositoryEntry = Tkinter.Entry(self)
searchRepositoryEntry.grid(row=1, column=0)
# list box
searchResults = Tkinter.Listbox(self)
searchResults.grid(row=2, column=0)
##### event handler
就在这里
searchRepositoryEntry.bind('<Key>',command = self.updateSearch)
# search results
for result in searchResultList:
searchResults.insert(Tkinter.END, result)
def updateSearch(self, event):
print('foo')
1 个回答
1
根据你示例中的缩进来看,updateSearch 似乎确实不是这个类的一部分。
假设缩进是个标记错误,并且根据你报告的错误信息,另一个问题是你重新定义了 self
,所以 'self.updateSearch' 指向的是顶层,而不是 EditStudentWindow 类。注意,错误信息是说 Toplevel instance has no attribute 'updateSearch'
,而不是 EditStudentWindow instance...
。
通常,这种小部件是通过继承来创建的,而不是组合。你可能需要考虑重新整理你的代码,让它看起来像这样:
class EditStudentWindowClass(Tkinter.Toplevel):
def __init__(self, *args, **kwargs):
Tkinter.Toplevel.__init__(self, *args, **kwargs)
self.title('Edit Students')
...