类内部的Tkinter事件处理程序出现问题

2024-04-26 10:45:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题是,我有一个类,它创建了一个Tkinter topclass对象,然后将一个字段放入其中,我想添加一个事件处理程序,该处理程序在每次按下按钮时运行一个方法(也在类中),但当调用事件时,它显示

AttributeError: Toplevel instance has no attribute '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 

right here

^{pr2}$

Tags: thetextselfbox处理程序titletkinter事件
1条回答
网友
1楼 · 发布于 2024-04-26 10:45:20

仅从示例的缩进判断,updateSearch似乎确实不是类定义的一部分。在

假设缩进是一个标记错误,并且基于您报告的错误消息,另一个问题是重新定义self,所以'自我更新搜索'指向顶层而不是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')
        ...

相关问题 更多 >