Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
590 views
in Technique[技术] by (71.8m points)

python - Closing current window when opening another window

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...