我努力奋斗了大约2个小时。.我看不出代码有什么问题。但这给了我这个错误。
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\82104\Anaconda3\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Users\82104\PycharmProjects\Macro\GUI.py", line 365, in on_entry_trace
self.co_button['state']=new_state
AttributeError: 'Description' object has no attribute 'co_button'
我不知道第1705行的第一个错误是什么意思,但是从第二个错误中我可以看到我的函数on_entry_trace
找不到self.co_button
。但是我找不到为什么不能。我发现很多人有这个问题,因为他们写得像
button = ttk.Button(something).grid(something)
代替
button = ttk.Button(something)
button.grid(something)
但这不是我的情况。
这是我遇到的问题。
class Description(tk.Toplevel):
def __init__(self, master=None):
super(Description, self).__init__(master=master)
self.title('Description')
self.grab_set()
self.geometry('206x100')
self.resizable(False, False)
self.label_ds = ttk.Label(self, text='Enter Text').grid(column=0, row=0, pady=(12, 4))
self.description = tk.StringVar()
entry_ds = ttk.Entry(self, width=25, textvariable=self.description)
entry_ds.grid(column=0, row=1, padx=13, pady=(0, 4))
entry_ds.focus()
self.description.trace('w', self.on_entry_trace)
self.description.set("")
self.co_button = ttk.Button(self, text='Confirm', command=self.on_press_ds)
self.co_button.grid(column=0, row=2, pady=4)
self.protocol("WM_DELETE_WINDOW", self.destroy_ds)
self.wait_visibility()
hide_minimize_maximize(self)
def on_entry_trace(self, *args):
new_state = "disabled" if self.description.get() == "" else "normal"
self.co_button.configure(state=new_state)
def on_press_ds(self):
description = self.description.get()
if description:
self.master.listbox.insert('end', '-- ' + description + ' --')
self.destroy_ds()
self.destroy()
def destroy_ds(self):
self.master.ds_button['state'] = 'normal'
self.destroy()
答案 0 :(得分:2)
出现此错误的原因是,进入小部件self.description.trace('w', self.on_entry_trace)
的跟踪方法在声明self.on_entry_trace
之前调用了co_button
方法。
我不知道第1705行的第一个错误是什么意思
这是主tkinter库中的行,由于文件中的第365行,return self.func(*args)
无法执行。
这是它的工作方式
Python的读取方式类似于...
....
entry_ds.focus()
# This will execute after above line
self.description.trace('w', self.on_entry_trace)
# Then goes through self.on_entry_trace()
...
# This will execute next
new_state = "disabled" if self.description.get() == "" else "normal"
# And here it'll throw an error as there is no attribute
self.co_button.configure(state=new_state)
...
self.description.set("")
....
# And you declared your button here
self.co_button = ttk.Button(self, text='Confirm', command=self.on_press_ds)
self.co_button.grid(column=0, row=2, pady=4)
因此,将self.description.trace('w', self.on_entry_trace)
放在__init__
的末尾将解决错误,并减少以后发生此类错误的可能性。
提示:
放置binds
和trace
或after
的最佳方法是在代码末尾,以避免这些小错误。这也取决于您的策略。