Moving objects in Tkinter
Matt McCredie
mccredie at gmail.com
Fri Oct 12 16:21:19 EDT 2007
On 10/12/07, Evjen Halverson <evjenh at yahoo.com> wrote:
> I have tried to make a Tkinter program make a rectangle move down the
> window, but did not succeed. All it does is make a rectangle trail.
> What am I doing wrong?
>
> from Tkinter import*
> root = Tk()
> RectangleColor='orange'
> Background=tk_rgb = "#%02x%02x%02x" % (100, 255, 100)
> root.geometry('1000x800+0+0')
> root.title("Moving Object Test")
> w = Canvas (root,width=1000,height=800,bg=Background)
> w.grid()
> import time
> t1=time.time()
> t2=t1
> ti=t2-t1
> x=100
> y=0
> a=0
> rect=Canvas.create_rectangle(w,x,y,200,100,fill=RectangleColor)
>
>
>
> def CLS():
>
> cls=Canvas.create_rectangle(w,0,0,1000,800,fill=Background)
> while ti<10:
> t2=time.time()
> ti=t2-t1
> y=y+10
>
> Canvas.create_rectangle(w,x,y,200,100,fill=RectangleColor)
>
> st1=time.time()
> st2=st1
> subti=st2-st1
> root.mainloop()
> time.sleep(100)
>
> while subti<1:
> st2=time.time()
> subti=st2-st1
> a=a+1
> CLS()
>
> #
> rect=Canvas.create_rectangle(w,x,y,1000,800,fill=RectangleColor)
>
>
>
> root.mainloop()
>
> quit()
Tkinter canvas works a little different than say, openGL or pygame.
You don't have to draw the rectangle over and over for each frame.
Every time you call create_rectangle you are creating another
rectangle. Another thing to note is that Tkinter has a built in
scheduler. You don't need to use time. The way you are calling Canvas
looks a little funny to me also.
Anyway, here is a simple example:
[code]
import Tkinter as tk
rectanglecolor = 'orange'
background = tk_rgb = "#%02x%02x%02x" % (100, 255, 100)
disty = 6
root = tk.Tk()
root.geometry('1000x800+0+0')
root.title("Moving Object Test")
can = tk.Canvas (root,width=1000,height=800,bg=background)
can.grid()
# note that rect is actually just an integer that is used to identify
that shape in the
# context of the canvas that it was created within.
rect = can.create_rectangle(400,0,600,200,fill=rectanglecolor)
for i in range(100):
# move the rectangle 0 in the x direction and disty in the y direction.
can.move(rect, 0, disty)
root.update() # update the display
root.after(30) # wait 30 ms
root.mainloop() # this just keeps the window open
[/code]
Matt
More information about the Python-list
mailing list