简体   繁体   English

如何在函数中关闭 tkinter 窗口后执行命令?

[英]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".新按钮将破坏新窗口,因此代码应该继续并打印“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.我发现 root2 的创建和销毁都很好,但是 "print("hi")" 行仅在 root1 关闭后运行。 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!我希望在单击“2”按钮后直接执行“print(”hi”) 行。任何想法将不胜感激。非常感谢!

You can extract the destruction of root2 in a helper function that will also execute the print('hi') you want.您可以在一个辅助函数中提取root2的破坏,该函数也将执行您想要的print('hi')

  • you probably do not need the lambdas: in this case, using the functions named is maybe better.您可能不需要 lambdas:在这种情况下,使用命名的函数可能更好。
  • You also probably are better off using a Toplevel instead of another call to Tk()您也可能最好使用Toplevel而不是另一个调用Tk()
  • It is also better to import tkinter as tk instead of a star import最好import tkinter as tk而不是星形导入

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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