首页 > 解决方案 > event.keycode 在 python 中不工作 tkinter

问题描述

在这里我只是设计一个简单的流浪游戏,我想使用Esc按钮退出游戏并使用Space按钮进行攻击。我在我的代码中使用了每个 mac 密钥代码,但它不起作用。这是我的 main.py:

 m = Utils.matrix
 def on_key_press(event):
    #exit
    if event.keycode == 53:
     print(event.keycode)
     root.destroy()

    #battle
    opponent = False
    for char in game.get_characters():
        if event.keycode == 49 and coords(hero) == coords(char):
            opponent = hero.battle(char)
    if opponent:
        game.remove_character(opponent)
    #initialise new game object and level up characters
    if game.get_char_length() < 1:
        new_level()
        game.create_monsters()
        game.level_up_chars(hero.level)
        hero.x = 0
        hero.y = 0
        hero.set_image(hero_down)

    canvas.delete("all")
    stats()
    draw_canvas()


canvas.bind("<KeyPress>", on_key_press)
canvas.pack()

在这里,我只是尝试创建一个单独的函数,但它仍然无法正常工作,其他类似的函数,如 keyup()、keydown() ... 工作正常,但对于“esc”和“space”没有。

m = Utils.matrix
def coords(char):
    x, y = char.get_coordinates()
    x, y = int(x / 72), int(y / 72)
    return x, y
def leftKey(event):
  if  m[coords(hero)[1]][coords(hero)[0] - 1] != 1 and coords(hero)[0] > 0: #left
     hero.move(x=-72)
     hero.set_image(hero_left)

def rightKey(event):
    if  m[coords(hero)[1]][coords(hero)[0]+1] != 1 and coords(hero)[0]<=9:   #right
     hero.move(x=72)
     hero.set_image(hero_right)

def upKey(event):
    if  m[coords(hero)[1] - 1][coords(hero)[0]] != 1 and coords(hero)[1] > 0:  # up
     hero.move(y=-72)
     hero.set_image(hero_up)

def downKey(event):
    if  m[coords(hero)[1] + 1][coords(hero)[0]] != 1 and coords(hero)[1] <= 9:  # down
     hero.move(y=72)
     hero.set_image(hero_down)

def close(event):
    # canvas.withdraw()  # if you want to bring it back
    # sys.exit() # if you want to exit the entire thing
    root.destry()

root.bind('<Escape>', close)

root.bind('<Left>', leftKey)
root.bind('<Right>', rightKey)
root.bind('<Up>', upKey)
root.bind('<Down>', downKey)
# root.bind("<KeyPress>", close)




enter code here

标签: pythontkintertkinter-canvaskeycode

解决方案


推荐阅读