Home > database >  using class inheritance on tkinter python
using class inheritance on tkinter python

Time:11-29

please help, I am trying to create a button on a tkinter window with the use of python class inheritance but it does not show the button. I am new to inheritance in python and not sure how do this. please see my code. thanks in advance

from tkinter import *

class A:
    def __init__(self):
        self.root = Tk()
        self.root.mainloop()
class B(A):
    def __init__(self):
        super().__init__()
        self.my_button = Button(self.root,text="test")
        self.my_button.pack()

d = B()

CodePudding user response:

It is not recommended (or should not) call tkinter mainloop() inside __init__() as mainloop() is a blocking function. Therefore super().__init__() will not return until the root window is closed. Since the button is created after super().__init__(), so the root window is blank.

Remove self.root.mainloop() inside A.__init__() and call tkinter mainloop() after you created instance of B():

from tkinter import *

class A:
    def __init__(self):
        self.root = Tk()
        # don't call mainloop() here

class B(A):
    def __init__(self):
        super().__init__()
        self.my_button = Button(self.root,text="test")
        self.my_button.pack()

d = B()
d.root.mainloop() # call mainloop() here
  • Related