0

There's the code I have:

import tkinter

class GuiEl(tkinter.Button):
    def __init__(self):
        self = tkinter.Button(rootfr, text = 'Test')
        self.grid(column = 1, row = 1)

    def command_set(self):    
        self.config(command=root.quit)

root = tkinter.Tk()
root.title('Test')

rootfr = tkinter.Frame(root)
rootfr.grid(column = 2, row = 2)

button1 = GuiEl()
button1.command_set()

root.mainloop()

What I want is to create a class, then make an instance - Button. Then I want to use a method on this instance (actually doesn't matter if it's done using the method of class or directly using the parent method) - config, which will modify this instance. What I get is:

Traceback (most recent call last):
  File "class_try.py", line 18, in <module>
    button1.command_set()
  File "class_try.py", line 9, in command_set
    self.config(command=root.quit)
  File "/usr/lib/python3.7/tkinter/__init__.py", line 1485, in configure
    return self._configure('configure', cnf, kw)
  File "/usr/lib/python3.7/tkinter/__init__.py", line 1476, in _configure
    self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
AttributeError: 'GuiEl' object has no attribute 'tk'

I've been googling for hours but can't deal with it. Kindly asking for your assistance. I know there's no reason to use classes in this situation, but I'm trying to learn how to do this.

1 Answers1

2

You aren't properly initializing your class.

Remove this line which is creating a second button:

self = tkinter.Button(rootfr, text = 'Test')

... and add this line, which properly initializes the current button:

tkinter.Button.__init__(self, text="Test")

Or even better if you're on python3:

super().__init__(text="Test")
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685