我实质上是在尝试不断更新tkinter GUI窗口中嵌入的图形,并且正在使用 after 函数在指定时间(10毫秒)后调用更新函数。但是,在执行回调时出现上述错误,并且我对tkinter和Python OOP还是很陌生,所以我很可能会犯一个基本错误。这是代码(在def update_plot中发生错误):
class PageThree(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Graph Page!", font=LARGE_FONT)
label.pack(pady=10,padx=10)
button1 = ttk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button1.pack()
global f, a
f = Figure(figsize=(5,5), dpi=100)
a = f.add_subplot(111)
canvas = FigureCanvasTkAgg(f, self)
canvas.show()
canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
toolbar = NavigationToolbar2TkAgg(canvas, self)
toolbar.update()
canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
readbutton = ttk.Button(self, text="Start Data Collection", command=self.read_data)
readbutton.pack()
stopbutton = ttk.Button(self, text="Stop Data Collection",
command=self.stop_data)
stopbutton.pack()
def read_data(self):
t_axis = []
global starttime
starttime = time()
self.update_plot()
def update_plot(self):
global func_id
t_axis.append(time()-starttime)
output.append(random.random())
a.cla()
a.plot(t_axis, output)
func_id = tk.Tk.after(samplerate, self.update_plot) # this is where it runs into an error
def stop_data(self):
global func_id
tk.Tk.after_cancel(func_id)
完全回溯错误是:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Users/.../anaconda/lib/python3.5/tkinter/__init__.py", line 1550, in __call__
return self.func(*args)
File "./gui2.py", line 202, in read_data
self.update_plot()
File "./gui2.py", line 211, in update_plot
func_id = tk.Tk.after(samplerate, self.update_plot)
File "/Users/.../anaconda/lib/python3.5/tkinter/__init__.py", line 592, in after
self.tk.call('after', ms)
AttributeError: 'int' object has no attribute 'tk'
我对此很困惑,在其他地方也没有找到类似的问题。有指针吗?
答案 0 :(得分:2)
您的问题似乎在您的事后声明中。
tk.Tk
不是您想的那样。
使用after()
时,您经常将其应用于root
窗口,或者在上课时更经常地将其应用于self
。
所以改变:
tk.Tk.after(samplerate, self.update_plot)
收件人:
self.after(samplerate, self.update_plot)