Z
Z
zlodiak2014-01-29 16:22:34
Python
zlodiak, 2014-01-29 16:22:34

Why inheritance in tkinter?

Please tell me why when creating graphical interfaces using tkinter it is customary to inherit a class from Frame, etc.?
Here is a classic code example that is almost always used:

import tkinter
import tkinter.messagebox

class Quitter(tkinter.Frame):        
                 
    def __init__(self, parent=None):          
        tkinter.Frame.__init__(self, parent)
        self.pack()
        widget = tkinter.Button(self, text='Quit', command=self.quit)
        widget.pack(side='left', expand='yes', fill=tkinter.BOTH)

    def quit(self):
        ans = tkinter.messagebox.askokcancel('Verify exit', "Really quit?")
        if ans: tkinter.Frame.quit(self)

if __name__ == '__main__':  Quitter().mainloop()

In my opinion, you can do without inheritance. For example like this:
import tkinter
 
class But_print():
     def __init__(self, parent):
          self.but = tkinter.Button(parent, text = 'press me', command = lambda: self.press(parent))
          self.but.pack()
          
     def press(self, parent):
          parent.destroy()
 
root = tkinter.Tk()
root2 = tkinter.Tk()
obj = But_print(root)
obj2 = But_print(root2)
root.mainloop()

Please tell me where I'm wrong and why is it important to use inheritance? What are the benefits?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
OnYourLips, 2014-01-29
@OnYourLips

Encapsulation of logic in a logical unit.
You have everything piled up in the global area.

V
vseplan, 2020-10-02
@vseplan

The graphical interface is implemented as a subclass of the Frame class and therefore automatically becomes an attachable component - that is, we can add all the widgets created by this class as a single package to any other graphical interface; simply attach an instance of this class to the GUI. In simple terms - if you need only one widget and you are not going to use it anywhere else, then you can do without 'frame'. But if you create a group of widgets, then it is more convenient to place them in one frame, place them in a separate module (where there can be many such groups) and then import them, attach them to other interfaces in one fell swoop. I took this information from Mark Lutz's book "Python Programming" volume 1. pp. 89-90.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question