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
417 views
in Technique[技术] by (71.8m points)

python - Closing a window and opening a new one via a button in Tkinter

I was wondering if there was a way to open a new instance of Toplevel() and close the current one via the press of a button, i.e. close the current window and open a new one. Here is the code in question:

def start(self):
        self.name = tk.DoubleVar()
        name_w = tk.Toplevel(root)
        name_w.wm_title("Enter name")
        f1 = tk.Frame(name_w)
        f1.pack()
        L1 = tk.Label(f1, text="Please enter your name!")
        L1.grid(row=0, column=0)
        E1 = tk.Entry(f1, textvariable=self.name)
        E1.grid(row=1, column=0)
        N1 = tk.Button(f1, text="Next", command = self.Q1)
        N1.grid(row=2, column=0)

In this case, I want self.Q1 to be called, while also destroying name_w. Is there anyway to do this? Thanks.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Yes, it's possible. To close an instance of Toplevel simply destroy it. You'll need to save a reference to the window. In your case I would either have Q1 destroy the window, or make a separate function that calls Q1 and then destroys the window. It all depends on what the main purpose of Q1 is.

For example:

def start(self):
    ...
    self.new_window = name_w
    ...

def quit_window(self):
    self.Q1()
    self.new_window.destroy()

If you have multiple of these you might need to store the window references in a list or dictionary, but the basic mechanism is the same: use .destroy() to destroy the window.

This isn't the only way, of course. You could use lambda or functools.partial and a function that accepts the name of the window to destroy, or you could use nested functions, etc.


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

...