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

时间:2017-10-08 00:32:04

标签: python events lambda tkinter

我写了一个小型绘画游戏,但它目前使用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()

1 个答案:

答案 0 :(得分:1)

在您的第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表达式可以被认为是内联函数,每当调用内容时都会对其进行求值,并且在冒号之前传递参数。

如果您为每个箭头键复制此行,那么您应该得到所需的结果。