pythontkinterlabeltkinter-label

AttributeError: type object 'gui' has no attribute 'label'


I want to change a labeltext from outside of the class through a setter method in the class. Im just getting AttributeError: type object 'gui' has no attribute 'label'. I tried changing the text through label['text']; label.config(text = 'X')

from tkinter import *

class gui:
    def __init__(self):
        self.root = Tk()
        self.label = Label(self.root, text='Y')
        self.label.pack()
        self.button = Button(self.root, text='Click', command=self.__btnClick)
        self.button.pack()

        mainloop()

    def __btnClick(self):
        changeText()
        
    def setLabelText(self):
        self.label['text']= 'X'

def changeText():
    gui.setLabelText(gui)

if __name__ == '__main__':
    window = gui()

I dont know if it helps but heres my full code https://pastebin.com/bT43NgpH

Thank you for your help!


Solution

  • You have to call setLabelText on an instance of gui not on the class itself. When you call setLabelText in __btnClick you have to give the instance of gui as a parameter to this function. You've got the instance in the parameter self.

    So __btnClick should be altered to:

    def __btnClick(self):
        changeText(self)
    

    And changeText should be altered to:

    def changeText(the_window):
        the_window.setLabelText()
    

    I'd like to add a link to the Style Guide for Python Code. Your code is hard to read for an experienced programmer (OK, not that hard, but harder than necessary) because you don't follow the naming conventions.