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
| import tkinter as tk
SIZE = 500
canvas = tk.Canvas(width=SIZE, height=SIZE)
canvas.pack()
boxes = []
for x, y in [[10, 10], [300, 10], [300, 300]]:
boxes += [ canvas.create_rectangle(x, y, x + 100, y+100, fill='blue') ]
cercle = canvas.create_oval(200, 100, 240, 140, fill='red')
directions = {
'Up' : (0, -20),
'Down' : (0, 20),
'Left' : (-20, 0),
'Right': (20, 0),
}
def move(event):
dx, dy = directions[event.keysym]
x0, y0, x1, y1 = canvas.bbox(cercle)
x0 += dx; x1 += dx
y0 += dy; y1 += dy
if x0 < 0 or x1 > SIZE or y0 < 0 or y1 > SIZE:
return
overlaps = canvas.find_overlapping(x0, y0, x1, y1)
for iid in overlaps:
if iid in boxes:
break
else:
canvas.move(cercle, dx, dy)
for key in directions:
canvas.bind('<%s>' % key, move)
canvas.focus_set()
tk.mainloop() |