我有以下代码工作正常,直到我在程序结束时添加了while循环,基本上试图保持循环运行永远(更新屏幕),直到窗口关闭。_tkinter.TclError:无法调用“更新”命令:应用程序已被破坏错误
while 1:
tk.update_idletasks()
tk.update()
time.sleep(0.01)
在加入上面的代码,以现有的代码,程序运行,但在出口,与此错误出现:
_tkinter.TclError: can't invoke "update" command: application has been destroyed error
我已经看到了类似的问题与此对于这个特定的问题没有任何答案可以帮助我解决这个问题。
整个代码如下:
问题/问题:是什么原因造成这个错误,我该如何解决?
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)
canvas=Canvas(tk,bg="white",width=500,height=400,bd=0,highlightthickness=0)
canvas.pack()
tk.update()
class Ball: #create a ball class
def __init__(self,canvas,color): #initiliased with the variables/attributes self, canvas, and color
self.canvas=canvas #set the intiial values for the starting attributes
self.id=canvas.create_oval(30,30,50,50,fill=color) #starting default values for the ball
""" 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) #this moves the oval to the specified location
def draw(self): #we have created the draw method but it doesn't do anything yet.
pass
ball1=Ball(canvas,'green') #here we are creating an object (green ball) of the class Ball
while 1:
tk.update_idletasks()
tk.update()
time.sleep(0.01)
说明更新:
另外,值得说明的是:
主循环是一个程序的核心部分和IDLE已经有一个主循环 - 但是如果你运行这个程序在IDLE之外,画布将出现,然后在瞬间消失后消失。要阻止窗口关闭,我们需要一个动画循环 - 因此while 1:.....否则,作为用户在下面评论,我们不需要while 1:因为IDLE已经有了这个地方(它可以在IDLE中正常工作,而无需使用while 1:..等等)
只是固定的代码缩进 - 对不起 – MissComputing
边注:避免使用'睡眠()'和'的wait()'用Tkinter的。这些方法对tkinter来说效果不佳。改用'after()'。 –