How to access method of an object in the object?

Viewed 67

I am trying to condense my code, so I want to create object instead of having to create labels each time I need one.

However, I can't figure out how to be able to change attributes of the object-labels using .config. I've tried using objectvariable.config(...), but that doesn't work. Neither does using a method like in the following:

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

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

Error-message is: objectvariable object has no attribute config.

How can I use .config on an object containing a label?

2 Answers

It should be

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 hold the reference to the class itself. label is something that your class is supposed to hold not to be. Another approach would be to derive from the Label class, but for what it is worth storing the label in the field should be good enough for you.

If you made your class a subclass of tkinter.Label then it would have inherited a config() method from it.
Here's an example of how that might be done:

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()

But as you can see, there wouldn't really be much point of doing so, since the only thing update() does is forward to call on the base class.

Related