python升级命令出现错误_python - _tkinter.TclError:无法调用“ update”命令:应用程序已被破坏错误 - 堆栈内存溢出...
我同意其他人的看法,您应该在这里使用mainloop() ,但是,如果您想保留原始代码的方式是跟踪布尔值, while x == True 。 这样,我们可以将x的值更新为False ,这样就可以避免发生错误。
当应用关闭时,我们可以使用protocol()方法更新布尔值。
如果我们将其添加到您的代码中:
x = True
def update_x():
global x
x = False
tk.protocol("WM_DELETE_WINDOW", update_x)
并将您的while语句更改为:
while x == True:
tk.update_idletasks()
tk.update()
time.sleep(0.01)
因此,您的完整代码可能如下所示:
from tkinter import *
import random
import time
tk=Tk()
tk.title("My 21st Century Pong Game")
tk.resizable(0,0)
tk.wm_attributes("-topmost",1)
x = True
def update_x():
global x
x = False
tk.protocol("WM_DELETE_WINDOW", update_x)
canvas=Canvas(tk,bg="white",width=500,height=400,bd=0,highlightthickness=0)
canvas.pack()
tk.update()
class Ball:
def __init__(self,canvas,color):
self.canvas=canvas
self.id=canvas.create_oval(30,30,50,50,fill=color)
""" Note: x and y coordinates for top left corner and x and y coordinates for the bottom right corner, and finally the fill colour for the oval
"""
self.canvas.move(self.id,0,0)
def draw(self):
pass
ball1=Ball(canvas,'green')
while x == True:
tk.update_idletasks()
tk.update()
time.sleep(0.01)
这将解决您的问题。
要重申其他人所说的,您真正需要的mainloop()此处的mainloop()而不是您的while i:语句。
mainloop()方法用于重置Tk()实例的循环。一旦代码到达显示tk.mainloop()的行,它将成为代码的下一个循环。
编写代码的正确方法是只使用mainloop()因为它会对mainloop()实例进行所有更新。
请参阅以下使用mainloop()代码:
from tkinter import *
tk=Tk()
tk.title("My 21st Century Pong Game")
tk.resizable(0,0)
tk.wm_attributes("-topmost",1)
canvas=Canvas(tk,bg="white",width=500,height=400,bd=0,highlightthickness=0)
canvas.pack()
tk.update()
class Ball:
def __init__(self,canvas,color):
self.canvas=canvas
self.id=canvas.create_oval(30,30,50,50,fill=color)
""" Note: x and y coordinates for top left corner and x and y coordinates for the bottom right corner, and finally the fill colour for the oval
"""
self.canvas.move(self.id,0,0)
def draw(self):
pass
ball1=Ball(canvas,'green')
tk.mainloop()
总结
以上是生活随笔为你收集整理的python升级命令出现错误_python - _tkinter.TclError:无法调用“ update”命令:应用程序已被破坏错误 - 堆栈内存溢出...的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: python计算消费总额_【数据分析案例
- 下一篇: python模拟通讯录的删除功能_pyt