[Tutor] Tkinter and Animation

Michael Lange klappnase at freenet.de
Thu Apr 28 11:20:40 CEST 2005


On Wed, 27 Apr 2005 19:31:06 -0700
Jeremiah Rushton <jeremiah.rushton at gmail.com> wrote:

> 
> I tried your idea and it doesn't animate it. I made a for loop and told it 
> to mover 1 pixel downward every .3 seconds for 25 times. It just waits till 
> the for loop is completed and then displays the result of the loop ending. I 
> also tried it without the for loop by writing each one of the steps out 
> repetively and I had the same result. The only thing that has kind of got 
> close to the visual is that I wrote a program that everytime the user 
> clicked the button it moved down one pixel, but I want it to move 100 
> pixels, one by one, with only one click from the user. Here's the code that 
> I wrote:
> 
> from Tkinter import *
> from time import sleep
> 
> class Main:
> 
> def __init__(self,master):
> button = Button(master,text='button')
> button.place(x=1,y=1)
> y=3
> for x in range(1,25):
> sleep(.3)
> button.place_forget()
> button.place(x=1,y=y)
> y+=2
> 
> 
> root = Tk()
> Main(root)
> root.title('test')
> root.mainloop()
> 
> Thanks for all the help so far.
> 
> Jeremiah
> 

Hi Jeremiah,

you should call update_idletasks() to make the changed geometry visible. I've written a (very quick and dirty)
demo that shows how to animate a Label with place() :

###########################################################

from Tkinter import *

class AnimatedFrame(Frame):
    def __init__(self, master, **kw):
        Frame.__init__(self, master, **kw)
        self.labelx = 100
        self.labely = 100
        self.label = Label(self, text='Look at me!')
        self.label.place(x=self.labelx, y=self.labely)
        self.button = Button(self, text='Start', command=self.start)
        self.button.place(x=100, y=200)
    
    def start(self):
        if self.labelx > 20:
            self.labelx -= 1
            self.labely -= 1
            self.label.place(x=self.labelx, y=self.labely)
            self.update_idletasks()
            self.start()

def test():
    root = Tk()
    f = AnimatedFrame(root, width=300, height=300)
    f.pack()
    root.mainloop()

if __name__ == '__main__':
    test()

#########################################################

I hope this helps

Michael


More information about the Tutor mailing list