Tkinter对象没有属性

时间:2015-09-23 01:55:02

标签: python tkinter

当我尝试调用updateText时,我在方法self.editArea.insert()下的python 2.7中收到以下错误。

AttributeError: 'App2' object has no attribute 'editArea'

我的代码是:

import Tkinter as tk
import threading

class App2(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)
        self.start()

    def callback(self):
        self.root.quit()

    def run(self):
        self.root = tk.Tk()
        self.root.protocol("WM_DELETE_WINDOW", self.callback)
        self.root.geometry("200x100")
        self.COMframe = tk.Frame(self.root, width=200, height=100, bg = '#ffffff', borderwidth=1, relief="sunken")
        self.scrollbar = tk.Scrollbar(self.COMframe)
        self.editArea = tk.Text(self.COMframe, width=200, height=100, yscrollcommand=self.scrollbar.set, borderwidth=0, highlightthickness=0)
        self.scrollbar.config(command=self.editArea.yview)
        self.scrollbar.pack(side="right", fill="y")
        self.editArea.pack(side="left", fill="both", expand=True)
        self.COMframe.grid(row=1, column=1)

        #self.editArea.config(state=tk.NORMAL)
        #self.editArea.delete(1.0, tk.END)
        self.editArea.insert(tk.END, "hello world\n this is my text")
        #self.editArea.config(state=tk.DISABLED)

        self.root.mainloop()

    def updateText(self, string):
        #self.editArea.config(state=tk.NORMAL)
        #self.editArea.delete(1.0, tk.END)
        self.editArea.insert(tk.END, string)
        #self.editArea.config(state=tk.DISABLED)

app2 = App2()

r = 0
while True:
    s = "r={}".format(r)
    app2.updateText(s)

    r = r+1
    print s

我不明白为什么python不会看到editArea。它是否与在run(self)中声明的事实有关?

1 个答案:

答案 0 :(得分:0)

您在self.editText方法中定义了run,但您从未调用过run方法(或者您通过一些您未向我们展示的代码来调用它)。

底线:您必须在尝试使用之前定义一个实例变量,但您的代码是在updateText之前调用run的顺序中运行的,这可以通过一对来证明印刷报表。