如何在对象中访问对象的方法?

How to access method of an object in the object?

我正在尝试压缩我的代码,所以我想创建对象而不是每次需要时都必须创建标签。

但是,我不知道如何使用 .config 更改对象标签的属性。我试过使用 objectvariable.config(...),但这不起作用。使用如下方法也不行:

class title_label():
    def __init__(self):
        self = tkinter.Label(root)
        self.pack(side='left')

    def update(self, text):
        self.config(text=text)

错误消息是:objectvariable object has no attribute config

如何在包含标签的对象上使用 .config

应该是

class title_label():
    def __init__(self, root):
        self.label = tkinter.Label(root)   # <<< 'label' field here
        self.label.pack(side='left')
    
    def update(self, text):
        self.label.config(text=text)

self 保存对 class 本身的引用。 label 是你的 class 应该 持有 而不是 的东西。另一种方法是从 Label class 派生,但对于值得将标签存储在字段中的内容,应该对您来说足够好。

如果你让你的 class 成为 tkinter.Labelsubclass 那么它会从它那里继承了 config() method
下面是一个如何做到这一点的例子:

import tkinter as tk


class TitleLabel(tk.Label):
    def update(self, text):
        self.config(text=text)


if __name__ == '__main__':
    root = tk.Tk()

    title_lbl = TitleLabel(root, text='Initial Text')
    title_lbl.pack(side='left')

    root.after(1000, lambda: title_lbl.update('CHANGED!'))  # Update after 1 sec.
    root.mainloop()

但是如您所见,这样做并没有多大意义,因为 update() 唯一要做的就是向前呼叫基地 class。