python - 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
解决方案
推荐阅读
- flutter - 从具有 n:m 关系的网络中获取数据并将其存储为模型类并在颤动的每一侧存储参考的正确方法是什么?
- mongodb - 是否可以使用 findAndUpdate 并排除某些字段?
- c# - 在 Autodesk Revit Forge Design Automation 中创建具有纹理的材质
- javascript - 如何将 JavaScript 中函数的认知复杂度从 10 降低到 6
- flutter - 参数类型 'CourseModel(其中 CourseModel 定义在 C:\Users\Ali Azad\Desktop\flutter\project\pro\lib\models\Course_model.dart)
- ios - Twilio Chat SDK iOS,通知徽章不适用于应用
- python - 用 Python 海龟图形制作的游戏
- swift - 如何快速执行命令来 ble 设备以从中检索值。命令返回的值将是字符串
- list - 带有乘法和加法 Python 的列表
- python - 如何使用 json 制作欢迎机器人?不和谐.py