Canvas上的物体用 bind_all(键值,事件函数(event)) 绑定后,就可用move(物体的id,横向移动坐标,纵向移动坐标) 来移动物体了。以下代码模拟了推箱子小游戏中箱子移动的动作,仅限制了边界暂没有添加其它箱子和砖墙等障碍物:
import tkinter as tk import pyautogui as ag def Box_Move(event): global x,y,w if event.keysym == "Up": if y-w>0: tCanvas.move(box,0,-w) tCanvas.move(box2,0,-w) tCanvas.move(pol,0,-w) y-=w elif event.keysym == "Down": if y+w<400-w: tCanvas.move(box,0,w) tCanvas.move(box2,0,w) tCanvas.move(pol,0,w) y+=w elif event.keysym == "Left": if x-w>0: tCanvas.move(box,-w,0) tCanvas.move(box2,-w,0) tCanvas.move(pol,-w,0) x-=w elif event.keysym == "Right": if x+w<400-w: tCanvas.move(box,w,0) tCanvas.move(box2,w,0) tCanvas.move(pol,w,0) x+=w def Window_Open(W, H): X, Y = ag.size() winSize = "%sx%s"%(str(W),str(H)) winPos = winSize + '+%s+%s'%(str((X-W)//2),str((Y-H)//2)) win.geometry(winPos) win.resizable(False, False) title = u'桌面分辨率:%sx%s%s窗体大小:%s'%(str(X),str(Y),' '*3,winSize) win.title(title) win.update() def Draw_Lines(w): for i in range(20,400,w): coord = 20,i,380,i tCanvas.create_line(coord) coord = i,20,i,380 tCanvas.create_line(coord) def Draw_Box(): global box,pol,box2 box = tCanvas.create_rectangle(x,y,x+w,y+w,width=2,fill='yellow') coord = (x+2,y+2,x+20,y+20,x+2,y+38,x+38,y+38,x+20,y+20,x+38,y+2) pol = tCanvas.create_polygon(coord,width=2,outline='green',fill='gold') box2 = tCanvas.create_rectangle(x+2,y+2,x+w-2,y+w-2,width=2,outline='red') if __name__ == '__main__': win = tk.Tk() Window_Open(400,400) tCanvas = tk.Canvas(win, width=win.winfo_width(), height=400, bg='honeydew') tCanvas.pack(side="top") x ,y, w = 100, 100, 40 Draw_Lines(w) Draw_Box() #绑定上下左右方向按键事件 tCanvas.bind_all("<KeyPress-Up>", Box_Move) tCanvas.bind_all("<KeyPress-Down>", Box_Move) tCanvas.bind_all("<KeyPress-Left>", Box_Move) tCanvas.bind_all("<KeyPress-Right>",Box_Move) win.mainloop()
效果图: