Advertisement
here2share

# Tk_move_obj.py

Jan 19th, 2022
1,343
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.07 KB | None | 0 0
  1. # Tk_move_obj.py
  2.  
  3. # imports every file form tkinter and tkinter.ttk
  4. from tkinter import *
  5. from tkinter.ttk import *
  6.  
  7. class GFG:
  8.     def __init__(self, master = None):
  9.         self.master = master
  10.          
  11.         # to take care movement in x direction
  12.         self.x = 1
  13.         # to take care movement in y direction
  14.         self.y = 0
  15.  
  16.         # canvas object to create shape
  17.         self.canvas = Canvas(master)
  18.         # creating rectangle
  19.         self.rectangle = self.canvas.create_rectangle(
  20.                          5, 5, 25, 25, fill = "black")
  21.         self.canvas.pack()
  22.  
  23.         # calling class's movement method to
  24.         # move the rectangle
  25.         self.movement()
  26.      
  27.     def movement(self):
  28.  
  29.         # This is where the move() method is called
  30.         # This moves the rectangle to x, y coordinates
  31.         self.canvas.move(self.rectangle, self.x, self.y)
  32.  
  33.         self.canvas.after(100, self.movement)
  34.      
  35.     # for motion in negative x direction
  36.     def left(self, event):
  37.         print(event.keysym)
  38.         self.x = -5
  39.         self.y = 0
  40.      
  41.     # for motion in positive x direction
  42.     def right(self, event):
  43.         print(event.keysym)
  44.         self.x = 5
  45.         self.y = 0
  46.      
  47.     # for motion in positive y direction
  48.     def up(self, event):
  49.         print(event.keysym)
  50.         self.x = 0
  51.         self.y = -5
  52.      
  53.     # for motion in negative y direction
  54.     def down(self, event):
  55.         print(event.keysym)
  56.         self.x = 0
  57.         self.y = 5
  58.  
  59. if __name__ == "__main__":
  60.  
  61.     # object of class Tk, responsible for creating
  62.     # a tkinter toplevel window
  63.     master = Tk()
  64.     gfg = GFG(master)
  65.  
  66.     # This will bind arrow keys to the tkinter
  67.     # toplevel which will navigate the image or drawing
  68.     master.bind("<KeyPress-Left>", lambda e: gfg.left(e))
  69.     master.bind("<KeyPress-Right>", lambda e: gfg.right(e))
  70.     master.bind("<KeyPress-Up>", lambda e: gfg.up(e))
  71.     master.bind("<KeyPress-Down>", lambda e: gfg.down(e))
  72.      
  73.     # Infinite loop breaks only by interrupt
  74.     mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement