是否可以通过来自 class 的 class 的函数访问来自 class 的 __init__ 的变量?

Is it possible to access a variable from a class's __init__ by a function from the same class?

我想在用户单击按钮时更改状态框中的文本。页面启动时的当前状态是“未加载文件”,单击按钮后,我希望此按钮上的文本更改为显示“文件已加载”或类似内容。

class PageOne(tk.Frame):
       
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="Load Data from Files", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        invButton = tk.Button(self, text="Load Inventory Data", command = self.openFile)
        invButton.pack()
        invStatusText = tk.StringVar()
        invStatusText.set("No file selected") 
        invStatus = tk.Button(self, state='disabled')
        invStatus.config(textvariable=invStatusText)
        invStatus.pack()
      
    def openFile(self):
        name = fd.askopenfilename()
        self.invStatusText.set("File Loaded")

当我 运行 没有将自身传递给 openFile() 时,它在进入带有消息 NameError: name 'invStatusText' is not defined 的 openFile 函数时出错。使用 self (上面的代码)时,我已经接近了。在这种情况下,我得到以下信息:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\anaconda3\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "<ipython-input-6-99355e7afb55>", line 84, in openFile1
    self.invStatusText.set("File Loaded")
AttributeError: 'PageOne' object has no attribute 'invStatusText'

所以我想通过更改 __init__ 函数中保存的变量的值来更改按钮 invButton 的文本,但它不允许我这样做。我在别处看到(我打开了大约 20 个 Whosebug 选项卡)这些变量应该在 class 级别定义,在 __init__ 之外但是当我试图将 invStatusText 放在 class 内部时我收到消息 AttributeError: 'NoneType' object has no attribute '_root'

__init__中,您需要将要调用的属性设为实例属性(通过向其添加 self):

class PageOne(tk.Frame):
       
    def __init__(self, parent, controller):
        ...
        self.invStatusText.set("No file selected") 
        ...
      
    def openFile(self):
        name = fd.askopenfilename()
        self.invStatusText.set("File Loaded")

此外,我想指出,您通常不打算在 __init__ 中做事。创建一个单独的方法来创建 UI 而不是在那里创建。随着你的 UI 长大,你的 __init__ 会变得难以理解。