Tkinter如何区分<key>和<control-key>绑定?

时间:2017-01-24 13:45:05

标签: python windows tkinter

这可能是一个简单的答案。

我有一个文本小部件,我想将任何字母数字键盘键(a-zA-Z0-9_和其他常规键)绑定到特定方法, Ctrl + F 到另一种方法。

使用widget.bind("<Key>", method)将创建以下内容:

  1. 点击 Ctrl + F 将调用method两次,一次用于 Ctrl event.keysym = Control_L, event.char = None),第二次用于 F event.keysym = f, event.char = <invalid>
  2. 点击 F 将调用methodevent.keysym = f, event.char = f
  3. 有没有办法区分这两种情景?

1 个答案:

答案 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()