2

I want my (Python/Windows) GUI GTK window to close on key press. However, there's no reaction. I'm a beginner and I was looking for answers in google. My english isn't very proffesional too. Please be patient with me.

import pygtk
import gtk
import pyHook

class Program:
    def QuitOnKeyPress(self):
        if pyHook.GetKeyState(81) == '1':
           gtk.main_quit()

def __init__(self):
    self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
    self.window.set_position(gtk.WIN_POS_CENTER)
    self.window.set_size_request(300, 300)
    self.window.show()

def main(self):
    gtk.main()


if __name__ == "__main__":
    prog = Program()
    prog.main()

while 1:
    prog.QuitOnKeyPress() #Tried without () too

Can you please tell me what am I doing wrong? I tried to use win32api and pyGame too. But win32api [from here] hasn't been installed, there was only win32com. PyGame had a problem too - there was no keyboard events/modules installed.

Nicolas
  • 37
  • 8

1 Answers1

1

Check out the pyHook tutorial. Your method of a while loop checking if a key is held down won't work well. Instead it should be like this:

def OnKeyboardEvent(event):
    if event.KeyID == 81:
        gtk.main_quit()

# return True to pass the event to other handlers
    return True

# create a hook manager
hm = pyHook.HookManager()
# watch for all mouse events
hm.KeyDown = OnKeyboardEvent
# set the hook
hm.HookKeyboard()
# wait forever
pythoncom.PumpMessages()
John Howard
  • 61,037
  • 23
  • 50
  • 66