I tried to use more than two windows using the Rushy Panchal example above. The intent was to have the change to call more windows with different widgets in them. The butnew function creates different buttons to open different windows. You pass as argument the name of the class containing the window (the second argument is nt necessary, I put it there just to test a possible use. It could be interesting to inherit from another window the widgets in common.
import tkinter as tk
class Demo1:
def __init__(self, master):
self.master = master
self.master.geometry("400x400")
self.frame = tk.Frame(self.master)
self.butnew("Window 1", "ONE", Demo2)
self.butnew("Window 2", "TWO", Demo3)
self.frame.pack()
def butnew(self, text, number, _class):
tk.Button(self.frame, text = text, width = 25, command = lambda: self.new_window(number, _class)).pack()
def new_window(self, number, _class):
self.newWindow = tk.Toplevel(self.master)
_class(self.newWindow, number)
class Demo2:
def __init__(self, master, number):
self.master = master
self.master.geometry("400x400+400+400")
self.frame = tk.Frame(self.master)
self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
self.label = tk.Label(master, text=f"this is window number {number}")
self.label.pack()
self.quitButton.pack()
self.frame.pack()
def close_windows(self):
self.master.destroy()
class Demo3:
def __init__(self, master, number):
self.master = master
self.master.geometry("400x400+400+400")
self.frame = tk.Frame(self.master)
self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
self.label = tk.Label(master, text=f"this is window number {number}")
self.label.pack()
self.label2 = tk.Label(master, text="THIS IS HERE TO DIFFERENTIATE THIS WINDOW")
self.label2.pack()
self.quitButton.pack()
self.frame.pack()
def close_windows(self):
self.master.destroy()
def main():
root = tk.Tk()
app = Demo1(root)
root.mainloop()
if __name__ == '__main__':
main()
Open the new window only once
To avoid having the chance to press multiple times the button having multiple windows... that are the same window, I made this script (take a look at this page too)
import tkinter as tk
def new_window1():
global win1
try:
if win1.state() == "normal": win1.focus()
except:
win1 = tk.Toplevel()
win1.geometry("300x300+500+200")
win1["bg"] = "navy"
lb = tk.Label(win1, text="Hello")
lb.pack()
win = tk.Tk()
win.geometry("200x200+200+100")
button = tk.Button(win, text="Open new Window")
button['command'] = new_window1
button.pack()
win.mainloop()