我知道并使用了大量的绑定语法,但是我怎么能直接检查事件对象并提取按下的字母,例如'c'和修饰符e,g,'Control'和'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
Run Code Online (Sandbox Code Playgroud)
偷了Python和Tkinter编程,但它没有显示我正在按的最终修饰符
从理论上讲,这将是您的问题的答案:
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()
Run Code Online (Sandbox Code Playgroud)
然而,它不应该工作 - 或者至少它不是我的匈牙利苹果键盘,这是一个110键布局..
无论如何,这里是事件对象的所有属性:http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/event-handlers.html
在Peter Varo 的想法的帮助下,我有点让它为我工作(运行 Windows 10 和 python 3.4)。
from tkinter import *
def onKeyDown(e):
# The obvious information
c = e.keysym
s = e.state
# Manual way to get the modifiers
ctrl = (s & 0x4) != 0
alt = (s & 0x8) != 0 or (s & 0x80) != 0
shift = (s & 0x1) != 0
# Merge it into an output
# if alt:
# c = 'alt+' + c
if shift:
c = 'shift+' + c
if ctrl:
c = 'ctrl+' + c
print(c)
# Run the tk window
root = Tk()
root.bind('<Key>', onKeyDown)
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
的alt关键是在我的情况下,越野车(它总是按下),但ctrl并shift工作正常。
请注意,第一次按下ctrl或shift键时,它会将其注册为主键而不是修饰键。如果你以后持有它,它只会是一个修饰符。
因此,您确实需要按组合键(如Ctrl+a)来按下它。结果,按下a然后ctrl会给出一个稍微奇怪的结果(它会忽略 a 并将 ctrl 标记为主键,而不是修饰符)。
| 归档时间: |
|
| 查看次数: |
3261 次 |
| 最近记录: |