tkinter case insensitive bind

2019-05-23 06:02发布

I've noticed that when you bind keys in tkinter (python3.2 winxp), the binds are case sensitive with the letter characters. In other words binding <Control-o> does not work if you press Control+o if caps lock is active. Does it mean I need to write two bindings for each case insensitive key combination with letter characters? Or is there any way to solve this?

Thanks for help :)

2条回答
放我归山
2楼-- · 2019-05-23 06:32

Yes, you have to make two bindings.

查看更多
爷、活的狠高调
3楼-- · 2019-05-23 06:36

You must bind twice in your case but you don't need to think about it once you write a clever function. Let's define a function that does this for us.

def bind_(widget, all_=False, modifier="", letter="", callback=None, add='',):
    if modifier and letter:
        letter = "-" + letter
    if all_:
        widget.bind_all('<{}{}>'.format(modifier,letter.upper()), callback, add)
        widget.bind_all('<{}{}>'.format(modifier,letter.lower()), callback, add)
    else:
        widget.bind('<{}{}>'.format(modifier,letter.upper()), callback, add)
        widget.bind('<{}{}>'.format(modifier,letter.lower()), callback, add)

And then use it like this:

bind_(text_widget, modifier="Control", letter="s", callback=save)
bind_(text_widget, modifier="Control-Shift", letter="s", callback=save_as)
bind_(text_widget, modifier="", letter="r", callback=print_something)
查看更多
登录 后发表回答