【发布时间】:2017-09-22 17:43:44
【问题描述】:
在我在程序末尾添加 while 循环之前,我的以下代码运行良好,这基本上是为了让循环永远运行(更新屏幕)直到窗口关闭。
while 1:
tk.update_idletasks()
tk.update()
time.sleep(0.01)
在将上述代码添加到现有代码时,程序运行,但在退出时...出现此错误:
_tkinter.TclError: can't invoke "update" command: application has been destroyed error
我在 SO 上看到了与此错误类似的问题,但没有针对此特定问题,并且没有任何答案对我的特定情况有帮助。
整个代码如下:
问题/问题:是什么导致了这个错误,我该如何解决?
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:..etc)
【问题讨论】:
-
刚刚修复了代码缩进 - 抱歉
-
旁注:避免在 tkinter 中使用
sleep()和wait()。这些方法不适用于 tkinter。请改用after()。