Python tkinter库画布键按钮事件移动对象(模拟推送盒小游戏)

Python tkinter库画布键按钮事件移动对象(模拟推送盒小游戏)

转自 Hann Yang 原文链接:https://blog.csdn.net/boysoft2002/article/details/115407588

Python tkinter库画布键按钮事件移动对象(模拟推送盒小游戏)

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

分享到 :

Leave a Reply

Your email address will not be published. Required fields are marked *