Moving objects in Tkinter
mccredie at gmail.com
Fri Oct 12 22:21:19 CEST 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()
> Background=tk_rgb = "#%02x%02x%02x" % (100, 255, 100)
> root.title("Moving Object Test")
> w = Canvas (root,width=1000,height=800,bg=Background)
> import time
> def CLS():
> while ti<10:
> while subti<1:
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:
import Tkinter as tk
rectanglecolor = 'orange'
background = tk_rgb = "#%02x%02x%02x" % (100, 255, 100)
disty = 6
root = tk.Tk()
root.title("Moving Object Test")
can = tk.Canvas (root,width=1000,height=800,bg=background)
# 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
More information about the Python-list