Search code examples
pythonpython-3.xtkinterbindkey-bindings

tkinter - how to bind just control, not control+key?


In Python 3 Tkinter, how do I bind just the control key to a widget, not <control-key>?
Normally, it's required to have another key also bound to it.


Solution

  • You would have to bind <Control_L> and <Control_R>

    import tkinter as tk
    
    def on_press(event):
        print(event)
    
    root = tk.Tk()
    root.bind('<Control_L>', on_press)
    root.bind('<Control_R>', on_press)
    root.mainloop()
    

    Eventually you can use <Key> which is executed with every key and then check event.keysym or event.code

    import tkinter as tk
    
    def on_press(event):
        print(event)
        print(event.keysym in ('Control_L', 'Control_R'))
        print(event.keycode in (37, 105))
    
    root = tk.Tk()
    root.bind('<Key>', on_press)
    root.mainloop()