[英]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')
。
Toplevel
instead of another call to Tk()
Toplevel
而不是另一个调用Tk()
import tkinter as tk
instead of a star importimport 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.