【问题标题】:Error when tkinter quits while using Pygame使用 Pygame 时 tkinter 退出时出错
【发布时间】:2019-04-04 17:13:41
【问题描述】:

我正在使用 pygame 和 tkinter 编写游戏,当我使用窗口的十字退出时,它会引发错误(但仍然成功退出): _tkinter.TclError:无法调用“更新”命令:应用程序已被销毁 我想停止这个错误信息 抛出错误的代码是'root.update'

我在https://gist.github.com/spacejoey86/4be3c84a32195ede0f798d3527c12874#file-second-revision上传了代码

【问题讨论】:

  • 请澄清您的具体问题或添加其他详细信息以准确突出您的需要。正如目前所写的那样,很难准确地说出你在问什么。请参阅How to Ask 页面以获得澄清此问题的帮助。
  • 很快:您应该分配/绑定到窗口的交叉函数,该函数将销毁窗口并设置您自己的变量is_tk_closed = True,稍后您将执行if not is_tk_closed: root.update()。这样root.update() 只会在 Tkinter 窗口仍然存在时执行。
  • 请不要链接到其他网站上的代码。您的问题应该有足够的代码供我们诊断问题。请edit您的问题包括minimal reproducible example

标签: python tkinter pygame


【解决方案1】:

您必须将函数分配给窗口的十字架,该函数将设置变量(即tk_open),然后您只能在窗口仍然存在时使用它来执行root.update()

代码基于 effbot.org 上的 Tkinter: Catching Window Deletion

您可以使用 root.protocol()root.bind() - 在 effbot.org 上阅读更多信息

import tkinter as tk

def _delete_window():
    global tk_open

    print("delete_window")

    tk_open = False
    root.destroy()

def _destroy(event):
    global tk_open

    print("destroy")

    tk_open = False

root = tk.Tk()
root.protocol("WM_DELETE_WINDOW", _delete_window)
#root.bind("<Destroy>", _destroy)

tk_open = True

while tk_open:
    root.update()

也许在你的代码中你只需要设置running == False 而不是使用tk_open

【讨论】:

  • 谢谢,我错过了全局位。
猜你喜欢
  • 1970-01-01
  • 2022-11-30
  • 2014-03-24
  • 1970-01-01
  • 2014-06-05
  • 2018-07-09
  • 2014-11-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多