Skip to content

Instantly share code, notes, and snippets.

@andy23512
Last active April 4, 2020 00:38
Show Gist options
  • Select an option

  • Save andy23512/bbfed43eb1d12ce14e375c258ea5857a to your computer and use it in GitHub Desktop.

Select an option

Save andy23512/bbfed43eb1d12ce14e375c258ea5857a to your computer and use it in GitHub Desktop.
from tkinter import *
import time
class Rectangle:
objects = []
@classmethod
def all_move_right(cls, event):
for obj in cls.objects:
obj.move_right(event)
@classmethod
def all_move_left(cls, event):
for obj in cls.objects:
obj.move_left(event)
def __new__(cls, *args, **kwargs):
instance = object.__new__(cls)
cls.objects.append(instance)
return instance
def __init__(self, canvas, y=100, color='yellow'):
self.canvas = canvas
self.y = y
self.color = color
self.x = 0
self.id = canvas.create_rectangle(230, self.y, 270, self.y + 20, fill=self.color)
def move_right(self, event):
self.x += 5
def move_left(self, event):
self.x -= 5
def move_action(self):
position = self.canvas.coords(self.id)
if position[0] > 360 and self.x > 0:
self.x = 0
elif position[0] < 100 and self.x < 0:
self.x = 0
self.canvas.move(self.id, self.x, 0)
root = Tk()
canvas1 = Canvas(root, width=500, height=300)
canvas1.pack()
rec1 = Rectangle(canvas=canvas1, y=100, color='blue')
rec2 = Rectangle(canvas=canvas1, y=200, color='green')
# bind event here only on canvas once
def on_keypress_right(event):
Rectangle.all_move_right(event)
def on_keypress_left(event):
Rectangle.all_move_left(event)
canvas1.bind_all('<KeyPress-Right>', on_keypress_right)
canvas1.bind_all('<KeyPress-Left>', on_keypress_left)
while True:
rec1.move_action()
rec2.move_action()
root.update()
time.sleep(0.1)
root.mainloop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment