Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Tkinter instance has no attribute 'tk'

AttributeError: MyGUI instance has no attribute 'tk'

Also, how do I make the created window have a fixed size and not be able to resize with the mouse? Or after changing label value by clicking on button.

My code:

from Tkinter import*

class MyGUI(Frame):

    def __init__(self):
        self.__mainWindow = Tk()    

    #lbl
        self.labelText = 'label message'
        self.depositLabel = Label(self.__mainWindow, text = self.labelText)

    #buttons
        self.hi_there = Button(self.__mainWindow)
        self.hi_there["text"] = "Hello",
        self.hi_there["command"] = self.testeo

        self.QUIT = Button(self.__mainWindow)
        self.QUIT["text"] = "QUIT"
        self.QUIT["fg"]   = "red"
        self.QUIT["command"] =  self.quit

    #place on view
        self.depositLabel.pack()
        self.hi_there.pack() #placed in order!
        self.QUIT.pack()

    #What does it do?
        mainloop()

    def testeo(self):

        self.depositLabel['text'] = 'c2value'

        print "testeo"

    def depositCallBack(self,event):
        self.labelText = 'change the value'
        print(self.labelText)
        self.depositLabel['text'] = 'change the value'

myGUI = MyGUI()

What's wrong? Thanks

like image 288
manuelBetancurt Avatar asked Jul 03 '26 09:07

manuelBetancurt


1 Answers

You should invoke the super constructor for Frame. Not sure, but I guess this will set the tk attribute that the quit command relies on. After that, there's no need to create your own Tk() instance.

def __init__(self):
    Frame.__init__(self)
    # self.__mainWindow = Tk()

Of course, you will also have to change the constructor calls for your widgets accordingly, e.g.,

self.hi_there = Button(self)  # self, not self.__mainWindow

or better (or at least shorter): set all the attributes directly in the constructors:

self.hi_there = Button(self, text="Hello", command=self.testeo)

Also add self.pack() to your constructor.

(Alternatively, you could change the quit command to self.__mainWindow.quit, but I think the above is better style for creating Frames, see e.g. here.)

like image 56
tobias_k Avatar answered Jul 05 '26 17:07

tobias_k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!