Python: TKinter - функции (команды в таблице).
canvas.move()
canvas.itemconfig()
canvas.coords()
event.keycode
- canvas.move(ob, x, y) - переместить ob в координаты x, y - по ним расположить левый верхний угол
- canvas.itemconfig(ob, fill="red", width="200") - изменить свойства объекта ob
- x1, y1, x2, y2 = canvas.coords(ob) получить координаты объекта ob
- canvas.coords(ob, x1, y1, x2, y2) установить новые координаты объекта ob
- event.keycode в keycode находится код нажатой клавиши (применяется в функции, вызываемой в bind())
"Пинг-Понг":
from tkinter import *
W, H, D, napr, napr2 = 800, 600, 40, 1, 1
px, py, pW, pH, napr_P = 430, H - 50, 300, 30, 1
cnt = 0
def update():
global x, y, px, napr, napr2, napr_P, cnt
# Шарик
if x == W - D:
napr = -1
elif x == 0:
napr = 1
x = x + napr
# отскок от прямоугольника
if y == py - D and px - D // 2 <= x <= px + pW + D // 2:
napr2 = -1
cnt += 1
elif y == H - D:
napr2 = -1
cnt -= 1
elif y == 0:
napr2 = 1
y = y + napr2
can.moveto(krug, x, y)
can.itemconfig(tablo, text=f"{cnt}")
# Прямоугольник
if px == W - pW:
napr_P = -1
elif px == 0:
napr_P = 1
px = px + napr_P
can.moveto(p, px, py)
win.after(2, update)
win = Tk()
win.title("I like to move it!")
can = Canvas(win, width=W, height=H, bg="lightcyan")
x, y = 10, 100
krug = can.create_oval(x, y, x + D, y + D, width=4, fill="BLUE")
p = can.create_rectangle(px, py, px + pW, py + pH)
tablo = can.create_text(W - 10, 40, text="0", font=('', 30), anchor=E)
can.pack(expand=True, fill=BOTH)
update()
win.mainloop()