Search code examples
python-3.xuser-interfacetkinteraccessibility

TKInter key bindings: how to prevent default GUI navigation behaviour?


In Tkinter, how do I override the default behaviour of keyboard navigation when binding to keys that are also used for navigation, like <Tab> or <space>? MWE to reproduce issue:

import tkinter
root = tkinter.Tk()

def tab():
    print("Tab was pressed")

def space():
    print("space was pressed")

A = tkinter.Button(root, text ="A")
A.pack()
B = tkinter.Button(root, text ="B")
B.pack()

root.bind("<Tab>", lambda x: tab())
root.bind("<space>", lambda x: space())

root.mainloop()

Solution

  • To prevent the default behavior, your function must return the string "break"

    def tab():
        print("Tab was pressed")
        return "break"
    
    def space():
        print("space was pressed")
        return "break"