键盘模块在 Tkinter 的第一个事件中没有检测到按键

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

假设你有这段代码。

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

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

就在第一次尝试按住shift并按回车时,它打印False,但之后它工作正常(第一次触发此事件,如果按住shift,则未检测到,但之后它有效)。

您可以像这样使用@martineau 在评论 check if modifier key is pressed in tkinter 中指出的内容:

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 是一个整数,它保存触发事件时按下的不同组合键的标志。 & 0x0001 检查事件触发时是否按下了 shift 键。