我有以下代碼工作正常,直到我在程序結束時添加了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()'。 –