pythonfunctiontkinterkey-bindings

How can I correctly unbind this function?


 win.bind("<Key>",menuKeys)

def menuKeys(event):
    global canvas, canwidth, canheight, blockwidth, blockheight
    if event.keysym == settings["keys"]["other"]["stop"]: 
        x,y = blockPoint("center")
        x -= 6
        y -= 3
        for i in range(5):
            for j in range(10):
                Spot(x+j,y)
            y += 1
        Text(x+3.5,y-2,"[Y/N]",color="blue",size=2)
        Text(x,y-5,"Are you sure you want",color="black",size=2)
        Text(x,y-4,"to quit?",color="black",size=2)
        win.bind("<Key>",stop)
        
def stop(event):
    if event.keysym == settings["keys"]["prompt-keys"]["yes"]:
        win.destroy()
    elif event.keysym == settings["keys"]["prompt-keys"]["no"]:
        x,y = blockPoint("center")
        x -= 6
        y -= 3
        for i in range(5):
            for j in range(10):
                Spot(x+j,y,color="#232627",outline="#232627")
            y += 1
        win.unbind("<Key>",stop)
    else:
        win.bind("<Key>",stop)

The menukeys function, when the key is pressed, calls the stop function. When pressing 'no', it deletes the area, but then I can't press 'quit' again to do this. What is the problem?


Solution

  • After pressing no there is no handler for the <Key> event. That's the reason pressing the quit key again doesn't work You need to rebind handler after pressing no.

    elif event.keysym == settings["keys"]["prompt-keys"]["no"]:
        x, y = blockPoint("center")
        x -= 6
        y -= 3
        for i in range(5):
            for j in range(10):
                Spot(x + j, y, color="#232627", outline="#232627")
            y += 1
        win.bind("<Key>", menuKeys)