AttributeError: 'MyReturnWindow' object has no attribute 'selected_index'

AttributeError: 'MyReturnWindow' object has no attribute 'selected_index'

因此,我在第二个(return) window:

中得到了以下代码

为什么我在return电影中会出现上述错误: 索引 = self.selected_index.get()

我知道return电影功能不起作用,我只是想知道为什么会出现该错误?

    def returnMovie(self):
        returningAccount = controll1.GetAccount(self.Input.get())
        return_dialog = MyReturnWindow(self, returningAccount)
        self.wait_window(return_dialog)

class MyReturnWindow(Toplevel):
    def __init__(self, parent, Account):
        super().__init__(parent)
        self.second_frame = Frame(self)
        self.second_frame.pack(fill=BOTH, expand=True)
        self.myReturnButton = Button(self, text='Return', command=self.returnMovie(Account))
        self.myReturnButton.pack(side=LEFT)

        self.selected_index = IntVar(self, -1)
        self.item_source = Variable(self, Account.get_movies())
        self.item_source.set(Account.get_movies())

        self.listbox_return = Listbox(self.second_frame, listvariable=self.item_source)
        self.listbox_return.bind("<<ListboxSelect>>", self.listbox_return_selection_changed)
        self.listbox_return.pack(fill=BOTH, expand=True)

    def listbox_return_selection_changed(self, event):
        index = self.listbox_return.curselection()[0]
        self.selected_index.set(index)
        self.selected_movie.set(controll1.GetMovies()[index])

    def returnMovie(self, Account):
        index = self.selected_index.get()
        movie = self.selected_movie.get()
        if index in range(0, self.listbox_return.size()):
            controll1.GetAccountMovies(Account).pop(index)
            controll1.GetMovies().pop(index)
            self.item_source.set(controll1.GetAccountMovies(Account))
        else:
            messagebox.showerror('No Movie found', 'There was no movie found')

你因为这行代码而得到错误:

self.myReturnButton = Button(self, text='Return', command=self.returnMovie(Account))

上面的代码和这个完全一样:

result = self.returnMovie(Account)
self.myReturnButton = Button(self, text='Return', command=result)

因此,您在设置 self.selected_index 之前调用 self.returnMovie(Account),因此当它尝试引用该属性时会抛出错误。

设置 command 选项时,您必须提供一个 callable —— 本质上是函数的 name。通常你应该提供一个不需要参数的命令,但由于你的命令需要一个参数,那么一个简单的解决方案是使用 lambda:

self.myReturnButton = Button(..., command=lambda: self.returnMovie(Account))