I want to create a program where I can create a main window and it's multiple toplevels , using classes . However , when I run my code given below , it creates 'multiple main windows and multiple toplevels' and not 'one main window and multiple toplevels' . Can anyone please recommend me how can I do this ?
from tkinter import *
class tk_window:
def __init__(self, root, exit_button):
self.root = root
self.exit_button = exit_button
self.root = Tk()
self.root.geometry('500x500')
self.exit_button = Button(self.root, text='EXIT', command=self.root.destroy)
self.exit_button.place(x=0, y=0)
Label(self.root, text='Vk').place(x=100, y=100)
class tk_toplevel(tk_window):
def __init__(self, top_level, root, exit_button):
super().__init__(root, exit_button)
self.top_level = top_level
self.exit_button = exit_button
self.top_level = Toplevel(self.root)
self.exit_button = Button(self.top_level, text='EXIT', command=self.top_level.destroy)
self.exit_button.place(x=0, y=0)
root2 = tk_toplevel('top_level1', 'root', 'exit_button1')
root3 = tk_toplevel('top_level2', 'root', 'exit_button2')
root4 = tk_toplevel('top_level3', 'root', 'exit_button3')
root5 = tk_toplevel('top_level4', 'root', 'exit_button4')
root1 = tk_window('root', 'exit_button')
root1.root.mainloop()
CodePudding user response:
You get multiple main windows because your top-level inherits from the main window. Thus, every instance of tk_toplevel
is a tk_window
, and also creates an instance of Toplevel
.
If you don't want more than one tk_window
, don't create a class that inherits from it. Instead, just inherit from Toplevel
and then don't create a separate instance of Toplevel
class tk_toplevel(Toplevel):
def __init__(self, top_level, root, exit_button):
super().__init__(root, exit_button)
self.top_level = top_level
self.exit_button = exit_button
self.exit_button = Button(self, text='EXIT', command=self.destroy)
self.exit_button.place(x=0, y=0)
Also, you should pass in the actual root window, not a string that is the same as the name of the root window.
root2 = tk_toplevel('top_level1', root, 'exit_button1')
root3 = tk_toplevel('top_level2', root, 'exit_button2')
root4 = tk_toplevel('top_level3', root, 'exit_button3')
root5 = tk_toplevel('top_level4', root, 'exit_button4')
Unrelated to the question being asked, you should read the PEP8 naming guidelines. It will make your code easier to understand. For your code that means to start your class names with an uppercase character.