This code explains to you how you can make a new window from a root window. This is the most simple code you can make. From this one you can make as many window as you want.
To make them you need:
- a call to new_window method inside the Win class (with a button for example) for each window
- to make a class (Win1 for example) for each window
import tkinter as tk
class Win:
def __init__(self, root):
"""Define window for the app"""
self.root = root
self.root.geometry("400x300")
self.root["bg"] = "coral"
self.button_rename = tk.Button(self.root, text = "New window",
command= lambda: self.new_window(Win2)).pack()
def new_window(self, _class):
self.new = tk.Toplevel(self.root)
_class(self.new)
class Win2:
def __init__(self, root):
self.root = root
self.root.geometry("300x300+200+200")
self.root["bg"] = "navy"
if __name__ == "__main__":
root = tk.Tk()
app = Win(root)
app.root.title("Lezioni")
root.mainloop()
Avoiding opening the same window more than once
There could be a problem: you can open as many window like Win2 as many times as you press the button, but what if you want only one of this window and not myltiple ones? You can change the code of the new_window:
def new_window(self, _class):
try:
if self.new.state() == "normal":
self.new.focus()
except:
self.new = tk.Toplevel(self.root)
_class(self.new)
The whole code:
import tkinter as tk
class Win:
def __init__(self, root):
"""Define window for the app"""
self.root = root
self.root.geometry("400x300")
self.root["bg"] = "coral"
self.button_rename = tk.Button(self.root, text = "New window",
command= lambda: self.new_window(Win2)).pack()
def new_window(self, _class):
try:
if self.new.state() == "normal":
self.new.focus()
except:
self.new = tk.Toplevel(self.root)
_class(self.new)
class Win2:
def __init__(self, root):
print(app.new.state())
self.root = root
self.root.geometry("300x300+200+200")
self.root["bg"] = "navy"
if __name__ == "__main__":
root = tk.Tk()
app = Win(root)
app.root.title("Lezioni")
root.mainloop()
Without buttons
If you want to open the window without buttons…
import tkinter as tk
def new_window(_class):
new = tk.Toplevel(win)
_class(new)
class Win2:
def __init__(self, root):
self.root = root
self.root.geometry("300x300+500+200")
self.root["bg"] = "navy"
def nw():
new_window(Win2)
win = tk.Tk()
win.geometry("200x200+200+100")
button = tk.Button(win, text="New Window")
button['command'] = nw
button.pack()
text = tk.Text(win, bg='cyan')
text.pack()
new_window(Win2)
win.mainloop()
Tkinter test for students
Tkinter articles