python升级命令出现错误_python - _tkinter.TclError:无法调用“ update”命令:应用程序已被破坏错误 - 堆栈内存溢出...
我同意其他人的看法,您應(yīng)該在這里使用mainloop() ,但是,如果您想保留原始代碼的方式是跟蹤布爾值, while x == True 。 這樣,我們可以將x的值更新為False ,這樣就可以避免發(fā)生錯(cuò)誤。
當(dāng)應(yīng)用關(guān)閉時(shí),我們可以使用protocol()方法更新布爾值。
如果我們將其添加到您的代碼中:
x = True
def update_x():
global x
x = False
tk.protocol("WM_DELETE_WINDOW", update_x)
并將您的while語(yǔ)句更改為:
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)
這將解決您的問(wèn)題。
要重申其他人所說(shuō)的,您真正需要的mainloop()此處的mainloop()而不是您的while i:語(yǔ)句。
mainloop()方法用于重置Tk()實(shí)例的循環(huán)。一旦代碼到達(dá)顯示tk.mainloop()的行,它將成為代碼的下一個(gè)循環(huán)。
編寫代碼的正確方法是只使用mainloop()因?yàn)樗鼤?huì)對(duì)mainloop()實(shí)例進(jìn)行所有更新。
請(qǐng)參閱以下使用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()
總結(jié)
以上是生活随笔為你收集整理的python升级命令出现错误_python - _tkinter.TclError:无法调用“ update”命令:应用程序已被破坏错误 - 堆栈内存溢出...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python计算消费总额_【数据分析案例
- 下一篇: python模拟通讯录的删除功能_pyt