简体   繁体   English

Python 中的移位和大写锁定状态

[英]Status of shift and caps lock in Python

I'm writing a TkInter application using Python 2.5 and I need to find out the status of the caps lock and shift keys (either true or false).我正在使用 Python 2.5 编写 TkInter 应用程序,我需要找出大写锁定和 shift 键的状态(真或假)。 I've searched all over the net but cant find a solution.我已经搜索了整个网络,但找不到解决方案。

Keyboard events in Tkinter can be tricky. Tkinter 中的键盘事件可能很棘手。

I suggest you have a look at the following, in order:我建议您按顺序查看以下内容:

Here is a program that displays the value of the keycode and state event parameters.这是一个显示键码值和 state 事件参数的程序。 You can use this to experiment.你可以用它来做实验。 Click in the window, then hit the keyboard.点击 window,然后敲击键盘。

from Tkinter import *
root = Tk()

def key(event):
    print "Keycode:", event.keycode, "State:", event.state

def callback(event):
    frame.focus_set()
    print "clicked at", event.x, event.y

frame = Frame(root, width=100, height=100)
frame.bind("<Key>", key)
frame.bind("<Button-1>", callback)
frame.pack()

root.mainloop()

Use:利用:

from Tkinter import *
root = Tk()
caps_lock_on = False
def CAPSLOCK_STATE():
    import ctypes
    hllDll = ctypes.WinDLL ("User32.dll")
    VK_CAPITAL = 0x14
    return hllDll.GetKeyState(VK_CAPITAL)

CAPSLOCK = CAPSLOCK_STATE()
if ((CAPSLOCK) & 0xffff) != 0:
    print "\nCaps lock is on\n"
    caps_key_on = True
else:
    caps_key_on = False
    print 'Caps lock is off'

def caps_lock_pressed(event=''):
    global caps_lock_on
    if caps_lock_on == False:
        caps_lock_on = True
        print 'Caps lock is on'
    else:
        caps_lock_on = False
        print 'Caps lock is off'

#Changes if shift key is on and off 
def shift_key_pressed(event=''):
    global shift_key_on
    shift_key_on = True
    print 'Shift is being holded' 

def shift_key_released(event=''):
    global shift_key_on
    shift_key_on = False
    print 'Shift has been released'
        
root.bind('<Caps_Lock>',caps_lock_pressed)
root.bind('<Shift_L>',shift_key_pressed)
root.bind('<Shift_R>',shift_key_pressed)
root.bind('<KeyRelease-Shift_R>',shift_key_released)
root.bind('<KeyRelease-Shift_L>',shift_key_released)
root.mainloop()

This will check if its caps lock, and then it will bind caps lock and shift to change the state.这将检查它的大写锁定,然后它将绑定大写锁定并转换以更改 state。 The caps lock detecting system is borrowed.大写锁定检测系统是借用的。

I googled and got one.. I am not sure whether it works for you for all keys...我用谷歌搜索了一个..我不确定它是否适用于所有键...

http://www.java2s.com/Code/Python/Event/KeyactionFunctionKeyALtControlShift.htm http://www.java2s.com/Code/Python/Event/KeyactionFunctionKeyALtControlShift.htm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM