将函数的lambda绑定到键事件python



我写了一个小型绘画游戏,但它目前使用GUI按钮而不是读取按键。

我如何使它读取按键,以获得与GUI按钮当前所做的相同的输出?

我根本无法使密钥绑定事件正常工作。我应该把它们绑定到其他东西上,还是我只是写错了?

(很抱歉代码墙,我尽可能地缩短了)

from tkinter import *
playerPos=0   
length=9
width=9

class GridTools:
#make a 2d array of Labels
def __init__(self,root):
self.grid=[]
acc=-1# keep track of the number of loops. Will be 0 by the time
#it's on a button
for x in range (0,length):
for y in range(0,width):
acc+=1
tile=Label(bg="black",fg="white",text=str(acc))
self.grid.append(tile)
tile.grid(row=x,column=y)
PlayerTile.makePlayer(self.grid)#put player in the grid
#add movement buttons
#I still don't understand Lambdas
moveUp= Button(text="up", command=lambda :PlayerTile.movePlayer(self.grid,"UP"))
moveUp.grid(row=11, column=11)
moveDown= Button(text="down", command=lambda :PlayerTile.movePlayer(self.grid,"DOWN"))
moveDown.grid(row=13, column=11)
moveLeft= Button(text="left", command=lambda :PlayerTile.movePlayer(self.grid,"LEFT"))
moveLeft.grid(row=12, column=10)
moveRight= Button(text="right", command=lambda :PlayerTile.movePlayer(self.grid,"RIGHT"))
moveRight.grid(row=12, column=12)
#this doesn't do anything
moveUp.bind('<Up>',lambda: layerTile.movePlayer(self.grid,"UP"))
#Manipulate the green player tile
class PlayerTile:
def makePlayer(grid):
global playerPos
grid[playerPos].config(bg="green")
def movePlayer(grid,direction):
global playerPos
if(direction=="UP" and playerPos>8):
grid[playerPos].config(bg="grey")
playerPos= playerPos -9
grid[playerPos].config(bg="green")
if(direction=="DOWN" and playerPos<(width-1)*length):
grid[playerPos].config(bg="light blue")
playerPos= playerPos +9
grid[playerPos].config(bg="green")
if(direction=="LEFT" and (playerPos)%length!=0):
grid[playerPos].config(bg="light pink")
playerPos= playerPos -1
grid[playerPos].config(bg="green")
if(direction=="RIGHT" and (playerPos+1)%length!=0):
grid[playerPos].config(bg="light yellow")
playerPos= playerPos +1
grid[playerPos].config(bg="green")

root=Tk() 
x=GridTools(root)#initialilize the grid using GridTools' init function
root.mainloop()

在您的行moveUp.bind('<Up>',lambda: layerTile.movePlayer(self.grid,"UP"))中,您正在将Up密钥绑定到moveUp小部件。

为了获得您想要的效果,您需要将其绑定到root:

root.bind('<Up>', lambda e: layerTile.movePlayer(self.grid,"UP"))

请注意,我将e(事件)传递给lambda表达式。lambda表达式可以被认为是一个内联函数,其中每当调用内容时都会对其进行求值,并且参数会在冒号之前传递。

如果你为每个箭头键复制这一行,那么你应该会得到你想要的结果。

最新更新