pythontkinterkeyboardpython-keyboard

keyboard module does not detect key-press on the first event of Tkinter


Suppose you have this code.

def test(widget):
    print(keyboard.is_pressed("shift"))

t=tkinter.Tk()
b=tkinter.scrolledtext.ScrolledText()
b.bind("<Return>", test)
b.pack()
t.mainloop()

Just on the very first try of holding shift and pressing enter, it prints False but after that it works fine (the first time this event is triggered, if shift is held down, it is not detected, but after that it works).


Solution

  • You can use what @martineau pointed out in the comments check if modifier key is pressed in tkinter like this:

    import tkinter as tk
    from tkinter.scrolledtext import ScrolledText
    
    def test(event):
        # If you want to get the widget that fired the event, use this:
        widget = event.widget
    
        # Check if the shift key is pressed when the event is fired
        shift_pressed = bool(event.state & 0x0001)
        if shift_pressed:
            ...
        else:
            print("Shift isn't pressed.")
    
    root = tk.Tk()
    text_widget = ScrolledText(root)
    text_widget.bind("<Return>", test)
    text_widget.pack()
    root.mainloop()
    

    event.state is an integer that holds flags for different keys combinations that are pressed when the event is fired. The & 0x0001 checks to see if the shift key is pressed when the event is fired.