I have the following code that worked fine until I added the while loop at the end of the program, which basically seeks to keep the loop running forever (updating the screen) until the window is closed.
while 1:
tk.update_idletasks()
tk.update()
time.sleep(0.01)
On adding the above code to the existing code, the program runs, but on exit ...comes up with this error:
_tkinter.TclError: can't invoke "update" command: application has been destroyed error
I have seen a similar question with this error on SO, but none for this specific problem and none of the answers could help for my specific case.
The whole code is below:
Question/Problem: What is causing this error and how can I fix it?
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)
Explanation update:
It is also worth explaining that:
the main loop is the central part of a program and IDLE already has a main loop - BUT if you run this program OUTSIDE of IDLE, the canvas will appear and then disappear after a split second. To stop the window from closing we are in need of an animation loop - hence the while 1: ..... otherwise, as a user commented below, we don't need the while 1: as IDLE already has this in place (it works fine in IDLE without the use of while 1:..etc)