Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Tk_key_move.py
- from Tkinter import *
- root = Tk()
- canvas = Canvas(root, width=400, height= 400, bg="white")
- canvas.pack()
- rect = canvas.create_rectangle(100, 100, 110, 110, fill='blue')
- x_velocity = 0
- y_velocity = 0
- keys_being_held_down = set()
- key_accelerations = {
- "Up": (0, -10),
- "Down": (0, 10),
- "Left": (-10, 0),
- "Right": (10, 0)
- }
- def key_pressed(event):
- global x_velocity, y_velocity
- #ignore autorepeat events
- if event.keysym in keys_being_held_down:
- return
- keys_being_held_down.add(event.keysym)
- acceleration = key_accelerations[event.keysym]
- x_velocity += acceleration[0]
- y_velocity += acceleration[1]
- def key_released(event):
- global x_velocity, y_velocity
- keys_being_held_down.remove(event.keysym)
- acceleration = key_accelerations[event.keysym]
- x_velocity -= acceleration[0]
- y_velocity -= acceleration[1]
- def tick():
- canvas.move(rect, x_velocity, y_velocity)
- root.after(50,tick)
- for key in key_accelerations:
- root.bind("<{}>".format(key), key_pressed)
- root.bind("<KeyRelease-{}>".format(key), key_released)
- root.after(100, tick)
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement