检查是否在 tkinter 中按下了修饰键 [英] check if modifier key is pressed in tkinter
问题描述
我知道并经常使用绑定语法,但是我怎样才能直接检查事件对象并提取两个按下的字母,例如'c' 和修饰符,例如,'Control' 和 'Alt' ?
I know and use a lot the syntax for binding, but how can I instead check directly the event object and extract both the letter pressed e.g. 'c' and the modifiers e,g,'Control' and 'Alt' ?
我试过了
def reportEvent(event):
eventDict = {
'2': 'KeyPress', '3': 'KeyRelease', '4': 'ButtonPress', '5': 'ButtonRelease', '6': 'Motion', '7': 'Enter',
'8': 'Leave', '9': 'FocusIn', '10': 'FocusOut', '12': 'Expose', '15': 'Visibility', '17': 'Destroy',
'18': 'Unmap', '19': 'Map', '21': 'Reparent', '22': 'Configure', '24': 'Gravity', '26': 'Circulate',
'28': 'Property', '32': 'Colormap','36': 'Activate', '37': 'Deactivate'}
rpt = '\n\n%s' % (80*'=')
rpt = '%s\nEvent: type=%s (%s)' % (rpt, event.type,eventDict.get(event.type, 'Unknown'))
rpt = '%s\ntime=%s' % (rpt, event.time)
rpt = '%s widget=%s' % (rpt, event.widget)
rpt = '%s x=%d, y=%d'% (rpt, event.x, event.y)
rpt = '%s x_root=%d, y_root=%d' % (rpt, event.x_root, event.y_root)
rpt = '%s y_root=%d' % (rpt, event.y_root)
rpt = '%s\nserial=%s' % (rpt, event.serial)
rpt = '%s num=%s' % (rpt, event.num)
rpt = '%s height=%s' % (rpt, event.height)
rpt = '%s width=%s' % (rpt, event.width)
rpt = '%s keysym=%s' % (rpt, event.keysym)
rpt = '%s ksNum=%s' % (rpt, event.keysym_num)
#### Some event types don't have these attributes
try:
rpt = '%s focus=%s' % (rpt, event.focus)
except:
try:
rpt = '%s send=%s' % (rpt, event.send_event)
except:
pass
print rpt
被盗到 Python 和 Tkinter 编程,但它没有显示我按下的最终修饰符
stolen to Python and Tkinter Programming,but it doesnt show the eventual modifiers I'm pressing
推荐答案
理论上这将是您问题的答案:
Theoretically this would be the answer for your problem:
from tkinter import *
root = Tk()
mods = {
0x0001: 'Shift',
0x0002: 'Caps Lock',
0x0004: 'Control',
0x0008: 'Left-hand Alt',
0x0010: 'Num Lock',
0x0080: 'Right-hand Alt',
0x0100: 'Mouse button 1',
0x0200: 'Mouse button 2',
0x0400: 'Mouse button 3'
}
root.bind( '<Key>', lambda e: print( 'Key:', e.char,
'Mods:', mods.get( e.state, None )))
root.mainloop()
但是,它无法正常工作——或者至少在我的 110 键布局的匈牙利苹果键盘上没有.
However, it is not working as it should be -- or at least it's not on my hungarian apple keyboard which is a 110 keys layout..
无论如何,这里是事件对象的所有属性:http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/event-handlers.html
Anyway, here are all the properties of the event object: http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/event-handlers.html
这篇关于检查是否在 tkinter 中按下了修饰键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!