AttributeError: 'int' object has no attribute 'tk'

AttributeError: 'int' object has no attribute 'tk'

我本质上是在尝试不断更新嵌入在 tkinter GUI 中的图形 window 并且我正在使用 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'

我对这个问题很困惑,在其他地方没有发现任何类似的问题。有什么指点吗?

您的问题似乎在您的后声明中。

tk.Tk 不是你想的那样。

当使用 after() 时,您经常将其应用于 root window 或更经常地在 class.

中应用于 self

所以改变:

tk.Tk.after(samplerate, self.update_plot)

收件人:

self.after(samplerate, self.update_plot)