这是先前问题的后续问题 ( python tkinter - 当按下备用键时检测箭头键 )
我还希望能够检测是否按下了功能键以及Shift键或控制键,同时按下了方向键之一(上、下、左、右)。
import tkinter
def on_key_press(event):
if event.state & 0x0001: # shift key
if event.keysym == 'Down':
print("shift and down arrow")
elif event.keysym == 'Up':
print("shift and up arrow")
elif event.keysym == 'Left':
print("shift and left arrow")
elif event.keysym == 'Right':
print("shift and right arrow")
elif event.state & 0x????: # shift key and function key 0x????
if event.keysym == 'Down':
print("shift and function and down arrow")
elif event.keysym == 'Up':
print("shift and function and up arrow")
elif event.keysym == 'Left':
print("shift and function and left arrow")
elif event.keysym == 'Right':
print("shift and function and right arrow")
elif event.state & 0x0004: # control key
if event.keysym == 'Down':
print("control and down arrow")
elif event.keysym == 'Up':
print("control and up arrow")
elif event.keysym == 'Left':
print("control and left arrow")
elif event.keysym == 'Right':
print("control and right arrow")
elif event.state & 0x????: # control key and function key 0x????
if event.keysym == 'Down':
print("control and function and down arrow")
elif event.keysym == 'Up':
print("control and function and up arrow")
elif event.keysym == 'Left':
print("control and function and left arrow")
elif event.keysym == 'Right':
print("control and function and right arrow")
elif event.state & 0x20000: # alternate key
if event.keysym == 'Down':
print("alternate and down arrow")
elif event.keysym == 'Up':
print("alternate and up arrow")
elif event.keysym == 'Left':
print("alternate and left arrow")
elif event.keysym == 'Right':
print("alternate and right arrow")
我希望有一对 0x???面具将使这一切变得容易。
这些是来自 text.bind(Key, function) 的 event.state 值
大写锁定关闭
大写锁定打开
以下代码演示了事件行为和 event.state 值。
等效的二进制值可以使用按位测试。
此代码只是将 event.state 值分组到元组中进行测试并显示结果。
from tkinter import Tk, LabelFrame, Text
master = Tk()
frame = LabelFrame(master, text = "Report")
frame.grid(sticky = "nsew")
text = Text(frame, undo = 1)
text.grid(sticky = "nsew")
def react(event):
if event.state in (5, 7, 262149, 262151):
k = f"ctrl+shift keys {event.state}"
elif event.state in (4, 6, 262148, 262150):
k = f"ctrl key {event.state}"
elif event.state in (1, 3, 262145, 262147):
k = f"shift key {event.state}"
elif event.state in (0, 2, 262144, 262146):
k = f"open key {event.state}"
else:
k = f"?? {event.keysym} & {event.state} ??"
result = f"{k} = {event.keysym}"
frame['text'] = result
print(result)
text.bind("<Key>", react)
text.focus_set()
master.mainloop()