简体   繁体   中英

How do I execute commands after a tkinter window closes in a function?

I have a window with a button, and I want that button to create a new window with a new button. The new button will destroy the new window, and as a result the code should progress and print "hi".

from tkinter import *

root1 = Tk()

def create():
    root2 = Tk()
    Button(root2,
            text="2",
            command=lambda: root2.destroy()).grid()
    root2.mainloop()
    print("hi")

Button(root1,
        text="1",
        command=lambda: create()).grid()

root1.mainloop()

What I am finding is that root2 is created and destroyed just fine, however the "print("hi")" line is only run after root1 is closed. I want the "print("hi") line to be executed straight after I click the button which says "2". Any ideas would be much appreciated. Thanks a lot!

You can extract the destruction of root2 in a helper function that will also execute the print('hi') you want.

  • you probably do not need the lambdas: in this case, using the functions named is maybe better.
  • You also probably are better off using a Toplevel instead of another call to Tk()
  • It is also better to import tkinter as tk instead of a star import

Maybe something like this:

import tkinter as tk                  # avoid star imports

def create_root2():
    def terminate():                  # helper to destroy root2 and print 'hi'
        print("hi", flush=True)
        root2.destroy()
    root2 = tk.Toplevel(root1)        # use tk.Toplevel i/o another call to tk.Tk()
    tk.Button(root2,
            text="-----2-----",
            command=terminate).grid() # call terminate w/o lambda (lambda is not useful here)

root1 = tk.Tk()
tk.Button(root1,
        text="-----1-----",
        command=create_root2).grid()  # call create_root2 w/o lambda (lambda is not useful here)

root1.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM