如何处理Python Tkinter程序中的窗口关闭事件(用户单击“X”按钮)?
发布于 2018-04-13 01:50:02
根据Tkinter活动,尤其是在使用Tkinter.after时,使用destroy()
停止此活动--即使使用协议()、按钮等--将干扰此活动(“执行时”错误),而不只是终止它。在几乎所有情况下,最好的解决方案都是使用标志。下面是一个关于如何使用它的简单、愚蠢的示例(尽管我确信大多数人不需要它!)
from Tkinter import *
def close_window():
global running
running = False # turn off while loop
print( "Window closed")
root = Tk()
root.protocol("WM_DELETE_WINDOW", close_window)
cv = Canvas(root, width=200, height=200)
cv.pack()
running = True;
# This is an endless loop stopped only by setting 'running' to 'False'
while running:
for i in range(200):
if not running:
break
cv.create_oval(i, i, i+1, i+1)
root.update()
这很好地终止了图形活动。您只需在正确的位置检查running
。
发布于 2020-12-07 03:03:43
如果您想更改x按钮的功能,或者使其无法关闭,请尝试此操作。
yourwindow.protocol("WM_DELETE_WINDOW", whatever)
那就无视“无论”是什么意思
def whatever():
# Replace this with your own event for example:
print("oi don't press that button")
您还可以这样做,以便在关闭该窗口时可以像这样回调它
yourwindow.withdraw()
这会隐藏窗口,但不会将其关闭
yourwindow.deiconify()
这将使窗口再次可见
发布于 2019-06-24 12:59:16
尝试简单的版本:
import tkinter
window = Tk()
closebutton = Button(window, text='X', command=window.destroy)
closebutton.pack()
window.mainloop()
或者,如果您想要添加更多命令:
import tkinter
window = Tk()
def close():
window.destroy()
#More Functions
closebutton = Button(window, text='X', command=close)
closebutton.pack()
window.mainloop()
https://stackoverflow.com/questions/111155
复制相似问题