Python tkinter库之Canvas按键事件移动物体 (模拟推箱子小游戏)

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()

效果图:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hann Yang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值