Why is the animation not working? The shape doesn't move when I run the program.
from Tkinter import *
import time
class alien(object):
def __init__(self):
self.root = Tk()
self.canvas = Canvas(self.root, width=400, height = 400)
self.canvas.pack()
alien1 = self.canvas.create_oval(20, 260, 120, 360, outline='white', fill='blue')
alien2 = self.canvas.create_oval(2, 2, 40, 40, outline='white', fill='red')
self.canvas.pack()
self.root.mainloop()
def animation(self):
track = 0
while True:
x = 5
y = 0
if track == 0:
for i in range(0,51):
self.time.sleep(0.025)
self.canvas.move(alien1, x, y)
self.canvas.move(alien2, x, y)
self.canvas.update()
track = 1
print "check"
else:
for i in range(0,51):
self.time.sleep(0.025)
self.canvas.move(alien1, -x, y)
self.canvas.move(alien2, -x, y)
self.canvas.update()
track = 0
print track
alien()
You never called the
animation
method. There were a couple of other naming issues.Your
animation
method has awhile True
loop in it which never breaks. This is a no-no in a GUI program, because by never returning, it prevents the GUI's event-loop from processing events. So, for example, if you had a Menu, then the user would not be able to select any menu item. The GUI would appear frozen, except for whatever actions you implement in theanimation
method.Here is a slight modification of @Tim's code which fixes this problem by removing the
while
loop and simply moving the aliens one step before returning.self.master.after
is called at the end of theanimation
method to have the event loop call animation again after a short pause.Here's a way of doing it using a loop:
An updatable variable is a variable that stays the same when updated and can be updated again.