Home > Mobile >  Trying to bind p to pause and unpause my Tkinter game
Trying to bind p to pause and unpause my Tkinter game

Time:11-28

I am currently making Snake in Tkinter, I want to bind the p button to pause my snake game, and when the user presses p again, it should unpause.

Here is some example code


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()

At the moment I can get the game to pause, but not unpause.

CodePudding user response:

This code snippet will pause and release any activity in function snakeMove. It is necessary to restart after when released from pause.

Also you need to make sure canvas has the focus or else key input will not work.

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()
  • Related