3

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). I've searched all over the net but cant find a solution.

4 Answers 4

3

Keyboard events in Tkinter can be tricky.

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. You can use this to experiment. Click in the window, then hit the keyboard.

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()
Sign up to request clarification or add additional context in comments.

Comments

1

Lock and Shift event modifiers:

http://infohost.nmt.edu/tcc/help/pubs/tkinter/event-modifiers.html

Comments

0

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

Comments

0

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. The caps lock detecting system is borrowed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.