英文:
How to continue programm after closing tkinter-window in python?
问题
我遇到了两个tkinter窗口的问题,我将其简化如下:
import tkinter as tk
def function_2(): # 创建窗口2
root2 = tk.Tk()
# 一些按钮,用于调用其他函数
root2.mainloop()
print(1) # 只是一个占位符,代表其他代码
def function_1(): # 创建窗口1
root = tk.Tk()
function_2()
root.mainloop()
function_1()
我希望在关闭窗口2之后执行function_2中的"print(1)",窗口2是在function_2中创建的,通过手动点击Windows窗口右上角的X来关闭。然而,只要我不关闭窗口1,输出"1"就不会显示出来。我应该怎么做才能得到期望的结果?
提前感谢!
我已经尝试过使用线程,因为我认为function_2中的代码似乎会等待function_1中的所有代码执行完毕。我还尝试了在function_2中的以下行的下方添加了以下代码:
root2.protocol("WM_DELETE_WINDOW", lambda: root2.destroy())
但结果是一样的:在关闭窗口2后,我没有返回到function_1。
英文:
I got a problem with two tkinter windows which I simplified as follows:
import tkinter as tk
def function_2(): # creates Window 2
root2 = tk.Tk()
# some buttons targeting other functions
root2.mainloop()
print(1) # just a placeholder for some other code
def function_1(): # creates Window 1
root = tk.Tk()
funtcion_2()
root.mainloop()
function_1()
I want the "print(1)" in function_2 to be executed after I close window 2, which is created in function_2, manually by clicking the X in the upper right corner of a Windows windows. However the output "1" won't show up as long as I don't close window 1 as well.
What shall I do to get the desired result?
Thanks in advance!
I already tried Threading cause I thought the code in function_2 seems to 'wait' until everything in function_1 is executed.
I also tried
root2.protocol("WM_DELETE_WINDOW", lambda: root2.destroy())
underneath the line
root2 = tk.Tk()
in function_2. But the result is the same: I don't return to function_1 after closing window 2.
答案1
得分: 2
建议只调用一次mainloop()
。同时避免使用多个Tk()
实例。
对于你的情况,可以使用root2.wait_window()
代替root2.mainloop()
:
def function2(): # 创建窗口2
root2 = tk.Tk()
# 一些按钮,用于调用其他函数
root2.wait_window() # 等待root2关闭
print(1)
请注意,你的代码中有一些拼写错误:
function_1()
应该是function1()
或者反过来function_2()
应该是function2()
或者反过来
英文:
It is recommended that mainloop()
should be called once. Also avoid using multiple instances of Tk()
.
For your case, use root2.wait_window()
instead of root2.mainloop()
:
def function2(): # creates Window 2
root2 = tk.Tk()
# some buttons targeting other functions
root2.wait_window() # wait for closing of root2
print(1)
Note that there are typos in your code:
function_1()
should befunction1()
or vice versafunction_2()
should befunction2()
or vice versa
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论