Advertisement
here2share

# Tk_key_move.py

Oct 17th, 2016
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.17 KB | None | 0 0
  1. # Tk_key_move.py
  2.  
  3. from Tkinter import *
  4. root = Tk()
  5. canvas = Canvas(root, width=400, height= 400, bg="white")
  6. canvas.pack()
  7. rect = canvas.create_rectangle(100, 100, 110, 110, fill='blue')
  8. x_velocity = 0
  9. y_velocity = 0
  10.  
  11. keys_being_held_down = set()
  12. key_accelerations = {
  13.     "Up": (0, -10),
  14.     "Down": (0, 10),
  15.     "Left": (-10, 0),
  16.     "Right": (10, 0)
  17. }
  18.  
  19. def key_pressed(event):
  20.     global x_velocity, y_velocity
  21.  
  22.     #ignore autorepeat events
  23.     if event.keysym in keys_being_held_down:
  24.         return
  25.  
  26.     keys_being_held_down.add(event.keysym)
  27.     acceleration = key_accelerations[event.keysym]
  28.     x_velocity += acceleration[0]
  29.     y_velocity += acceleration[1]
  30.  
  31. def key_released(event):
  32.     global x_velocity, y_velocity
  33.     keys_being_held_down.remove(event.keysym)
  34.     acceleration = key_accelerations[event.keysym]
  35.     x_velocity -= acceleration[0]
  36.     y_velocity -= acceleration[1]
  37.  
  38. def tick():
  39.     canvas.move(rect, x_velocity, y_velocity)
  40.     root.after(50,tick)
  41.  
  42. for key in key_accelerations:
  43.     root.bind("<{}>".format(key), key_pressed)
  44.     root.bind("<KeyRelease-{}>".format(key), key_released)
  45.  
  46. root.after(100, tick)
  47. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement