[Tkinter-discuss] up+right

Jeff Epler jepler at unpythonic.net
Tue May 9 23:41:43 CEST 2006

In this example program, the canvas item is moved in the direction
indicated by the arrow key(s) pressed.  It works by setting a "dx" value
when Left or Right is pressed, and then setting "dx" back to 0 when one
of those keys is released.  Approximately each 20ms the dx and dy values
are added to the location of the box, and it's moved on the canvas using
coords().  It's probably a good idea to set dx and dy to 0 when you see
a <FocusOut> event, because when you lose focus you may not see all the
KeyRelease events for keys that were pressed at the time.

import Tkinter

x = y = 150
dx = dy = 0

def wrap(v, l):
    v = v % l
    if v < 0: return v + l
    return v

def update():
    global x, y
    x = wrap(x + dx, 300)
    y = wrap(y + dy, 300)
    c.coords(item, (x-5, y-5, x+5, y+5))
    c.after(20, update)

def set_dx(v):
    global dx; dx = v
def set_dy(v):
    global dy; dy = v

t = Tkinter.Tk()
t.bind("<KeyPress-Up>", lambda e: set_dy(-3))
t.bind("<KeyPress-Down>", lambda e: set_dy(3))
t.bind("<KeyPress-Left>", lambda e: set_dx(-3))
t.bind("<KeyPress-Right>", lambda e: set_dx(3))
t.bind("<KeyRelease-Up>", lambda e: set_dy(0))
t.bind("<KeyRelease-Down>", lambda e: set_dy(0))
t.bind("<KeyRelease-Left>", lambda e: set_dx(0))
t.bind("<KeyRelease-Right>", lambda e: set_dx(0))

c = Tkinter.Canvas(t, width=300, height=300)
item = c.create_rectangle((-1,-1,-1,-1), fill="blue", outline="white")


More information about the Tkinter-discuss mailing list