Trouble with Tkinter event handler inside of a class
My problem is that I have a class that creates a Tkinter topclass object and then puts a field into it and I want to add an event handler that runs a method (that is also in the class) every time a button is pressed but when the event is called it says
AttributeError: Toplevel instance has no attribute 'updateSearch'
class EditStudentWindow():
def __init__(self):
searchResultList = ['student1', 'student2', 'student3'] # test list
##### window attributes
# create window
self = Tkinter.T开发者_StackOverflow中文版oplevel()
#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
right here
searchRepositoryEntry.bind('<Key>',command = self.updateSearch)
# search results
for result in searchResultList:
searchResults.insert(Tkinter.END, result)
def updateSearch(self, event):
print('foo')
Judging solely on the indentation of your example, it appears that updateSearch is indeed not part of the class definition.
Assuming the indentation is a markup mistake, and based on the error message you report, the other problem is that you redefine self
, so 'self.updateSearch' points to the toplevel rather than the EditStudentWindow class. Note that the message says Toplevel instance has no attribute 'updateSearch'
rather than EditStudentWindow instance...
Typically, such widgets are created with inheritance rather than composition. You might want to consider refactoring your code to look something like:
class EditStudentWindowClass(Tkinter.Toplevel):
def __init__(self, *args, **kwargs):
Tkinter.Toplevel.__init__(self, *args, **kwargs)
self.title('Edit Students')
...
精彩评论