【问题标题】:Trying to bind p to pause and unpause my Tkinter game试图绑定 p 以暂停和取消暂停我的 Tkinter 游戏
【发布时间】:2021-11-27 10:30:08
【问题描述】:

我目前正在Tkinter中制作Snake,我想绑定p按钮来暂停我的蛇游戏,当用户再次按下p时,它应该会取消暂停。

这是一些示例代码


def pause(is_paused):
            global paused
            paused = is_paused
        
            if (paused == True):
                paused = False

            else:
                # Somehow pause my game                                   
                paused = True
def snakeMove():
   ... #Lines of code to move snake
   master.after(50, snakeMove) # snakeMove is the function for moving the snake

canvas.bind("<p>", pause)
global paused
paused = False

master.mainloop()

目前我可以让游戏暂停,但不能取消暂停。

【问题讨论】:

  • 我不明白;我们应该告诉您如何撤消暂停操作,还是应该告诉您可以使用什么逻辑来触发取消暂停游戏?
  • 两者,我是 python 新手,更不用说 Tkinter,任何指导将不胜感激。

标签: python-3.x tkinter tkinter-canvas


【解决方案1】:

此代码 sn-p 将暂停并释放函数 snakeMove 中的任何活动。 解除暂停后需要重启after

您还需要确保画布具有焦点,否则按键输入将不起作用。

bound = None
paused = False

def pause(event):
    global paused
    paused = (paused == False)
    if not paused:
        print("Unpaused")
        bound = master.after(50, snakeMove)

def snakeMove():
    global bound
    if paused:
        master.after_cancel(bound)
        print("Paused")
    else:
        bound = master.after(50, snakeMove) # snakeMove is the function for moving the snake

canvas.bind("<Key-p>", pause)
bound = master.after(150, snakeMove)

canvas.focus_force()
master.mainloop()

【讨论】:

    猜你喜欢
    • 2016-01-09
    • 2015-06-01
    • 1970-01-01
    • 2016-09-02
    • 1970-01-01
    • 2015-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多