因此,我在第二个(返回)窗口中获得了以下代码:
为什么在returnMovie中出现上述错误:
索引= self.selected_index.get()
我知道returnMovie函数不起作用,我很好奇为什么会收到该错误?
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.returnMovie(Account)
之前先调用self.selected_index
,因此在尝试引用该属性时会引发错误。设置
command
选项时,必须提供一个可调用对象-本质上是函数的名称。通常,您应该提供不需要参数的命令,但是由于您的命令需要参数,因此一种简单的解决方案是使用lambda
:self.myReturnButton = Button(..., command=lambda: self.returnMovie(Account))
关于python - AttributeError:“MyReturnWindow”对象没有属性“selected_index”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53796189/