How do you check weather or not capslock is on on

2019-08-04 06:47发布

问题:

I found certain code in a pygame program, this to be exact:

caplock = False
for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
       if event.key == pygame.CAPSLOCK:
          capslock = True

    if event.type == pygame.KEYUP:
       if event.key == pygame.CAPSLOCK:
          capslock = False

when you press "caps lock" while it is off, capslock is

True

and when you press "caps lock" while it is on, capslock is

False

Instead of making capslock equal to False at the beginning, how can I make it equal to True if capslock is already on or False if it is already off?

回答1:

On Linux (tested on Linux Mint 18.1 with Python 3.6) you can use:

import subprocess
if subprocess.check_output('xset q | grep LED', shell=True)[65] == 50 :
    capslock = False
if subprocess.check_output('xset q | grep LED', shell=True)[65] == 51 :
    capslock = True
print( "capslock ON is : ", capslock )

If it doesn't work, check which values subprocess.check_output() gives you if CapsLock is ON and if CapsLock is OFF. Theoretically it should be 0 and 1, not 50, 51, but on my box it is 50, 51.

You can also take a look at "Python - How to get current keylock status?" for further information.

And YES, I think also you need a keypress event from Pygame to know the status of the keys, so to know it in advance you have to use a method from outside of Pygame.