YasserKad
YasserKad

Reputation: 21

Tkinter - How can I make a button can create new window and close the main window

Hello guys I want to make a button can close the main window (window01) and create new window (window02) This is my code but he does not working with me :

from tkinter import *
window01 = Tk()
def myButton():
   window02 = tk.Toplevel(window01)
   
button = Button(window01, text="Button", command=myButton)
button.pack()
window01.mainloop()

Upvotes: 1

Views: 72

Answers (2)

TheLizzard
TheLizzard

Reputation: 7680

I think you are looking for something like this:

import tkinter as tk

def myButton():
    window01.destroy()
    window02 = tk.Tk()
    # Code for your second window
    window02.mainloop()

window01 = tk.Tk()
button = tk.Button(window01, text="Button", command=myButton)
button.pack()
window01.mainloop()

When the button is clicked it destroys window01 and creates window02 and goes in window02's mainloop.

Upvotes: 1

tevemadar
tevemadar

Reputation: 13205

Copy-Paste dupli-duplication of your code:

from tkinter import *

nextStep = False

window01 = Tk()
def myButton():
   global nextStep
   nextStep = True
   window01.destroy()
   
button = Button(window01, text="Button", command=myButton)
button.pack()
window01.mainloop()

if nextStep:
   window01 = Tk()
   button = Button(window01, text="Button", command=myButton)
   button.pack()
   window01.mainloop()

If you just close the first window directly, nothing happens, if you press the button, the second window appears.

Upvotes: 0

Related Questions