这可能是一个简单的答案。
我有一个文本小部件,我想将任何字母数字键盘键(a-zA-Z0-9_和其他常规键)绑定到特定方法, Ctrl + F 到另一种方法。
使用widget.bind("<Key>", method)
将创建以下内容:
method
两次,一次用于 Ctrl (event.keysym = Control_L, event.char = None
),第二次用于 F (event.keysym = f, event.char = <invalid>
)method
(event.keysym = f, event.char = f
)有没有办法区分这两种情景?
答案 0 :(得分:4)
您可以绑定<Control-f>
和<f>
(和其他键一样)。
import tkinter as tk
# --- functions ---
def key_f(event):
print('key: f')
def key_shift_f(event):
print('key: Shift + f')
def key_control_f(event):
print('key: Control + f')
def key_control_shift_f(event):
print('key: Control+Shift + f')
# --- main ---
root = tk.Tk()
#root.bind("<f>", key_f) # it works too
#root.bind("<F>", key_shift_f) # it works too
root.bind("f", key_f)
root.bind("F", key_shift_f)
root.bind("<Control-f>", key_control_f)
root.bind("<Control-F>", key_control_shift_f)
root.mainloop()
或者,您可以使用event.state & 4
通过Control
识别密钥。
您需要按位&
,因为它会保留有关其他特殊键的信息
(请参阅http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/event-handlers.html上的Masks/Modifier
)
import tkinter as tk
# --- functions ---
def method(event):
print('-----')
print('[DEBUG] event.char :', event.char)
print('[DEBUG] event.keysym:', event.keysym)
print('[DEBUG] event.state :', event.state, '=', bin(event.state))
if event.char: # skip Control_L, etc.
# if you need `& 5` then it has to be before `& 4`
if event.state & 5 == 5: # it needs `== 5` because `& 5` can give results `5`, `4` or `1` which give `True` or `0` which gives `False`
print('method: Control+Shift +', event.keysym)
elif event.state & 4: # it doesn't need `== 4` because `& 4` can give only results `4` or `0`
print('method: Control +', event.keysym)
elif event.state & 1: # it doesn't need `== 1` because `& 1` can give only results `1` or `0`
print('method: Shift +', event.keysym)
else:
print('method:', event.keysym)
# --- main ---
root = tk.Tk()
root.bind("<Key>", method)
root.mainloop()