CTRL KeyPress 事件通过使用 TouchPad 滚动触发

问题描述 投票:0回答:2

我试图在按下和释放控制键时跟踪它。
虽然一开始一切似乎都很好,但是当我在 Windows 11 的 HP 笔记本电脑上使用触摸板滚动时,KeyPress 事件会自动触发。

这是 Windows 的东西并且是 正常行为 或者它是 tkinter 中的bug

我的代码:

import tkinter as tk
    
ctrl_pressed = None
    
def check_ctrl(event):
    print(ctrl_pressed, 'checked')
    
def track_ctrl(event):
    global ctrl_pressed
    if (et:=event.type.name) == 'KeyPress':
        ctrl_pressed = True
    elif et == 'KeyRelease':
        ctrl_pressed = False
    print(ctrl_pressed, 'tracked')
    
root = tk.Tk()
root.bind('<MouseWheel>', check_ctrl)
root.bind('<KeyPress-Control_L>', track_ctrl)
root.bind('<KeyRelease-Control_L>', track_ctrl)
root.mainloop()
  • 首先使用 MouseWheel 将输出
    None
    --如预期的那样。
  • 使用 触摸板首先会输出
    True
    --不是预期的。
  • 按下 键将首先输出
    True
    然后
    False
    --正如预期的那样。

好像是生成事件:

def track_ctrl(event):
    print(event.send_event)

这会产生带有触摸板的

True


我正在使用 Tkinter

8.6.12
的补丁级别和 Python 版本
3.11.0

python tkinter tcl tk-toolkit gesture
2个回答
2
投票

使用 Windows 10 专业版和 Python 3.11 我无法重现此行为。 您可以尝试使用键盘而不是 tkinter 来监听事件。

这是你的代码

keyboard.is_pressed
而不是检查
event.type

import tkinter as tk
from keyboard import is_pressed
ctrl_pressed = None

def check_ctrl(event):
    print(ctrl_pressed, 'checked')

def track_ctrl(event):
    global ctrl_pressed
    if is_pressed('ctrl'):
        ctrl_pressed = True
    else:
        ctrl_pressed = False
    print(ctrl_pressed, 'tracked')

root = tk.Tk()
root.bind('<MouseWheel>', check_ctrl)
root.bind('<KeyPress-Control_L>', track_ctrl)
root.bind('<KeyRelease-Control_L>', track_ctrl)
root.mainloop()

希望对您有所帮助!


-1
投票

我记得有这个问题,可能不是错误。当您使用触摸板进行滚动时,系统会自动激活和释放控制键,以允许用户使用缩放功能。 因此,这会生成一个 Key-Press 事件,然后是控制键的 Key-Release 事件。

如果你想忽略这个问题,试试这个代码

def track_ctrl(event): #Function
global pressed_ctrl #global var
if (et:=event.type.name) == 'KeyPress': #tracking the keypress through event type name
    if not event.send_event:
        pressed_ctrl= True
elif et == 'KeyRelease':
    if not event.send_event:
        pressed_ctrl= False
print(pressed_ctrl, 'tracked')

综上所述,该函数通过监听按键按下和松开事件来跟踪Control键当前是否被按下,并使用pressed_ctrl全局变量来存储当前按键的状态。该功能检查事件是否由用户生成,以避免受到合成事件的干扰。该函数将密钥的当前状态输出到控制台以进行调试。

© www.soinside.com 2019 - 2024. All rights reserved.