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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| import tkinter as tk
import time
def center(canvas, ident):
c = canvas.bbox(ident)
if c:
x0, y0, x1, y1 = c
return (x1 - x0) // 2, (y1 - y0) // 2
class Ball:
iid = None
cx, cy = None
def __init__(self):
self.iid = canvas.create_oval(100, 100, 140, 140, fill="blue", outline="blue")
self.cx, self.cy = center(canvas, self.iid)
def move(self, dx, dy):
canvas.move(self.iid, dx, dy)
self.cx += dx
self.cy += dy
@property
def next_position(self):
if self.cx + 1 < 500:
return self.cx+1, self.cy+1
balls = []
def create_ball():
b = Ball()
balls.append(b)
def on_left_click(e):
w = e.widget
create_ball()
timer = None
def do_update(delay=20):
global timer
now = time.clock()
for b in balls:
x0, y0 = b.cx, b.cy
x1, y1 = b.next_position
b.move(x1-x0, y1-y0)
rest = int(delay - (1000 * (time.clock() - now)))
assert rest > 2, 'fatal: rest=%.3f' % rest
timer = app.after(rest, do_update)
app = tk.Tk()
canvas = tk.Canvas(width = 600, height = 600, bg = "orange")
canvas.pack()
canvas.bind("<Button-1>",on_left_click)
do_update()
tk.mainloop() |
Partager