【问题标题】:turtle: How to stop all processes and close window when I click X button?乌龟:当我单击 X 按钮时,如何停止所有进程并关闭窗口?
【发布时间】:2020-04-13 06:17:58
【问题描述】:

我正在用 Python 3.7 编写一个程序,该程序在用户单击屏幕的位置绘制花朵,但我不知道如何检测用户是否在函数仍在执行时按下 X 按钮,然后停止所有进程并关闭窗口。

我寻找解决方案并尝试使用this 回答有关使用winfo_toplevel 的问题,但我也无法做到这一点。

我的代码如下所示:

import turtle, random
from sys import exit

window = turtle.Screen()
window.setup(1000,500)

#my functions to draw go here, but aren't included since the question is about closing the program  

def stop():
    turtle.bye()
    root.destroy()
    exit()

window.onclick(chooseFlower)
window.listen()

canvas = window.getcanvas()
root = canvas.winfo_toplevel()
root.protocol("WM_DELETE_WINDOW", stop)
while not root.protocol("WM_DELETE_WINDOW"):
    turtle.mainloop()

我收到了一堆错误:

tkinter.TclError: can't invoke "destroy" command: application has been destroyed

然后

raise Terminator
turtle.Terminator

然后

_tkinter.TclError: invalid command name ".!canvas"

我还能尝试什么?

【问题讨论】:

    标签: python python-3.7 turtle-graphics


    【解决方案1】:

    在您单击 X 按钮之前,您的代码正在破坏窗口。 while 循环条件错误。我认为您的代码应该在没有它的情况下运行。此外,turtle.bye() 将为您关闭窗口而不会出现任何错误。您不需要销毁函数来执行此操作。尝试按以下方式更改代码。它应该工作。

           def stop():
               turtle.bye()
    

    并注释掉

              root.protocol("WM_DELETE_WINDOW", stop)
              # while root.protocol("WM_DELETE_WINDOW"):
              turtle.mainloop()
    

    【讨论】:

    • 谢谢,这仍然会给我一个 turtle.Terminator 错误如果我在程序仍在绘图时关闭它,我该如何让它停止?
    猜你喜欢
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    • 2012-09-23
    • 1970-01-01
    • 2018-10-01
    • 2021-03-28
    • 1970-01-01
    • 2013-02-10
    相关资源
    最近更新 更多