首页 > 解决方案 > 检测移位+数字的键盘独立方式

问题描述

我希望能够检测到用户何时按下数字。这部分正在使用<Key-#>绑定(下面的代码)。Shift但是当用户按下+时,我需要做出不同的反应digits。我已经尝试过<Shift-#>,但它不起作用,因为按Shift+会创建与, , , , , , , , ,digits等字符对应的事件!@#$%¨&*()

人们可以“”这些字符,但问题是它们在所有键盘中的位置并不相同。

QWERTY - 英语 在此处输入图像描述

AZERTY - 用于比利时部分地区 在此处输入图像描述

不仅不同的布局(QWERTYAZERTYDVORAK等)不同,而且甚至两个不同的QWERTY键盘也可能因您的语言环境而异。(我的 qwerty 键盘¨的按键与图片中的6相反^

因此,“侦听 ,exclam内容是一种依赖于键盘的检测+的方式。dollarampersandShiftdigits

问题:我怎样才能以独立于键盘的方式做到这一点?

frame .f -padx 50 -pady 50
focus -force .f
label .f.digit_label -text "Digit:" -padx 50 -pady 20
label .f.keypress_label -text "KeyPress" -padx 50 -pady 20
pack .f
pack .f.digit_label
pack .f.keypress_label
bind .f <Key-1> {::digit_press %K}
bind .f <Key-2> {::digit_press %K}
bind .f <Key-3> {::digit_press %K}
bind .f <Key-4> {::digit_press %K}
bind .f <Key-5> {::digit_press %K}
bind .f <Key-6> {::digit_press %K}
bind .f <Key-7> {::digit_press %K}
bind .f <Key-8> {::digit_press %K}
bind .f <Key-9> {::digit_press %K}
bind .f <Key-0> {::digit_press %K}

bind .f <Shift-1> {::digit_press %K}
bind .f <Shift-2> {::digit_press %K}
bind .f <Shift-3> {::digit_press %K}
bind .f <Shift-4> {::digit_press %K}
bind .f <Shift-5> {::digit_press %K}
bind .f <Shift-6> {::digit_press %K}
bind .f <Shift-7> {::digit_press %K}
bind .f <Shift-8> {::digit_press %K}
bind .f <Shift-9> {::digit_press %K}
bind .f <Shift-0> {::digit_press %K}
bind all <Escape> {exit}
bind all <KeyPress> {::keypress %K}


proc ::digit_press {str} {
    .f.digit_label configure -text "Digit: $str"
}
proc ::keypress {str} {
    .f.keypress_label configure -text "KeyPress: $str"
}

标签: tcltk

解决方案


Most of the time when writing software, you want the cooked symbolic names of keys or the characters that they encode. Not in your case. Tk mostly hides the low level from you, but you can get at it if you're prepared to work at decoding it. In particular, if you do this in a raw wish:

bind . <Key> {
    puts "%A:::%s:::%k:::%K"
}

Then you can press keys and see what you get. Be aware that there's no actual guarantee that these will be the same for all keyboards! On mine (UK layout), pressing 1, 2, 3 followed by shift and the same three keys prints this:

1:::0:::26:::1
2:::0:::27:::2
3:::0:::28:::3
{}:::0:::68:::Shift_R
!:::1:::26:::exclam
@:::1:::27:::at
£:::1:::28:::sterling

As you can see, the %k field reports the keycode that does not change on shift status, and the %s field becomes 1 when the shift key is down (it's a bitmap, so use [expr {%s & 1}] to test that). You'll have to throw events away too.


推荐阅读