0

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()
2
  • The code you posted will not produce the error you referring to. Please provide a minimal reproducible example. Commented Nov 29, 2022 at 4:11
  • It is not recommended to call mainloop() inside __init__(). For your case, super().__init__() inside class B will return only after you close the main window, then you try to create button which raises the exception. Commented Nov 29, 2022 at 4:22

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.