0
votes

I have created a program in python 3.4 using the GUI module tkinter. I want to tweak the code so when a new window is called it will close the current window then open up the new window. As at the moment the current window is just placed behind the new window rather than destroying it. I have attempted to use .destroy() but that prevents the other window opening. I have my procedure which carries out the current window switch below.

    def help1(self):
      root2=Toplevel(self.master)
      HelpWindow= HelpScreen.Help(root2)

I understand this question is quite common but i cant find a soloution on here which would be applicable for my code.

1
Don't close, disable it ! Why ? What is sub window closing type ? grab_set / grab_release or withdraw / deiconify, You need handle closing method because Ex: if sub_window closed by system. need add status checker in main app if csub_window is exist - dsgdfg
An app should have one main Tk() window. When this is destroyed, game over (as you discovered). For what you want, hide the main with withdraw and create and destroy Toplevels. Or: create and destroy frames put within the main window. Or: put multiple frame on top of each other and .lift() the one you want to be visible. - Terry Jan Reedy
Questions like this have been asked before. You might try searching a bit. - Terry Jan Reedy

1 Answers

1
votes

You can destroy a toplevel window with the destroy() method. You shouldn't do this on the root window, but you can do it on any other window.

If you only ever want one window in your application, create a root window and then hide it and don't use it. Then, create the first real window as a Toplevel. From that point on you can easily destroy the current window and create a new window.

Here is a contrived example:

import tkinter as tk

root = tk.Tk()
root.withdraw()

current_window = None

def  replace_window(root):
    """Destroy current window, create new window"""
    global current_window
    if current_window is not None:
        current_window.destroy()
    current_window = tk.Toplevel(root)

    # if the user kills the window via the window manager,
    # exit the application. 
    current_window.wm_protocol("WM_DELETE_WINDOW", root.destroy)

    return current_window

counter = 0
def new_window():
    global counter
    counter += 1

    window = replace_window(root)
    label = tk.Label(window, text="This is window %s" % counter)
    button = tk.Button(window, text="Create a new window", command=new_window)
    label.pack(fill="both", expand=True, padx=20, pady=20)
    button.pack(padx=10, pady=10)

window = new_window()