1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| import tkinter as tk
DV = 5
DELAY = 50
motion_timer = None
motion_key = None
motion_deltas = {
'Left': (-DV, 0),
'Right': (DV, 0),
'Up': (0, -DV),
'Down': (0, DV),
}
def do_motion(canvas, dx, dy):
def _doit():
global motion_timer
canvas.move('bille', dx, dy)
motion_timer = canvas.after(DELAY, _doit)
_doit()
def on_key_press(canvas, keysym):
global motion_timer, motion_key
if motion_key != keysym:
if motion_timer is not None:
canvas.after_cancel(motion_timer)
motion_timer = None
motion_key = keysym
do_motion(canvas, *motion_deltas[keysym])
if __name__ == '__main__':
root = tk.Tk()
root.event_add('<<PressArrows>>',
'<KeyPress-Left>', '<KeyPress-Right>',
'<KeyPress-Up>', '<KeyPress-Down>')
canvas = tk.Canvas(width=600, height=600, bg='white')
canvas.bind('<<PressArrows>>', lambda e: on_key_press(e.widget, e.keysym))
canvas.create_oval(100, 100, 115, 115, fill='red', tag='bille')
canvas.pack()
canvas.focus_set()
on_key_press(canvas, 'Right')
tk.mainloop() |
Partager