-1

does anyone know how i can execute code by key press in python 2.7? I'm thinking that maybe i should make an invisible window and on key-press it executes code which i can have under a function? does anyone know how i can achieve that?

I'm trying to make something that takes screenshots and i have this, but i want it to be under a key-press instead of every time you run the program.

import wx
import random
import getpass
from time import gmtime, strftime
Time = strftime("%Y-%m-%d %H:%M:%S", gmtime())
User = getpass.getuser()
app= wx.App()
screen = wx.ScreenDC()
size = screen.GetSize()
bmp = wx.EmptyBitmap(size[0], size[1])
mem = wx.MemoryDC(bmp)
mem.Blit(0, 0, size[0], size[1], screen, 0, 0)
del mem  # Release bitmap
Time = Time.replace(':','-')
Name = Time + '.png'
Name = Name.replace(' ', '%20')
bmp.SaveFile(Name, wx.BITMAP_TYPE_PNG)

Is there anyway i can make this activate underkeypress?

user3651193
  • 51
  • 1
  • 1
  • 6
  • For key availabe in all system you will have to register this key in system or read keys directly from system - and it depends on system – furas Jul 12 '14 at 22:31
  • Look for some keylogger in Python - it knows how to grap pressed key. – furas Jul 12 '14 at 22:39

3 Answers3

0

You could use a minimized pygame window to get the key presses:

import pygame, sys
from pygame.locals import *
pygame.init()

windowSurface = pygame.display.set_mode((1, 1))

pygame.display.iconify()

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    if pygame.key.get_pressed()[pygame.K_UP]:
        #DO something if the player hits the UP arrow key
        print 'up!'
ZenOfPython
  • 891
  • 6
  • 15
0

Duplicate question I think, answer is here: Python read a single character from the user

The idea is to use the os library to implement the getch() function you would use if you were writing in C.

Community
  • 1
  • 1
chris
  • 4,840
  • 5
  • 35
  • 66
0

See: Set global hotkey with Python 2.6

Probably you could use pyHook if you use Windows.

Or some method used in pyKeylogger if you use Linux.

Seems you use wxPython so see RegisterHotKey in wxWindows

Community
  • 1
  • 1
furas
  • 134,197
  • 12
  • 106
  • 148