How can I make a command to open second window and close the main window in python.
The code can open the next window but it cant close the main window..
This is the code:
from tkinter import *
def main():
root = Tk()
app = first(root)
class first:
def __init__(self, master):
self.master = master
self.master.title("First")
tit = Label(self.master, text="Im the first page", font=20)
tit.place(relx=0.5, rely=0.4, anchor=CENTER)
sec = Button(self.master, text="Second", width=20, height=10,
bg="black", fg="white", command=self.second_open)
sec.place(relx=0.5, rely=0.5, anchor=CENTER)
def second_open(self):
self.secondwindow = Toplevel(self.master)
self.app = second(self.secondwindow)
class second:
def __init__(self, master):
self.master = master
self.master.title("Second")
tit = Label(self.master, text="Im the second page", font=20)
tit.place(relx=0.5, rely=0.4, anchor=CENTER)
if __name__ == "__main__":
main()
mainloop()
CodePudding user response:
tkinter is designed for you to create one root window, and keep that window until the program ends. That makes it difficult to do what you ask.
A better solution in many cases is to just keep and reconfigure the main window instead of destroying it and creating a new window.
Here's an example based on the code in the question:
def second_open(self):
for child in self.master.winfo_children():
child.destroy()
self.secondwindow = second(self.master)
