PyGTK Hotkey

Linux tutorials and code.
1 post Page 1 of 1
Contributors
User avatar
mikethedj4
VIP - Site Partner
VIP - Site Partner
Posts: 2592
Joined: Thu Mar 25, 2010 4:36 am

PyGTK Hotkey
mikethedj4
Today's tutorial is pretty simple, we're going to take a basic window (As created in this tutorial) and add a simple hotkey to it, and just to keep it super simple, we're going to have it so when users press the escape key; the window closes.

Lets startout with our basic window.
Code: Select all
#!/usr/bin/env python

import gtk

class app:

  def __init__(self):
	window = gtk.Window(gtk.WINDOW_TOPLEVEL)
	window.set_position(gtk.WIN_POS_CENTER)
	window.set_title("TestApp")
	window.set_default_size(320, 200)
	window.connect("destroy", gtk.main_quit)
	window.show_all()

app()
gtk.main()
Now before we make the hotkey lets add the following keypress signal, below the window destory signal.
Code: Select all
window.connect("key-press-event", self.closeapp)
Now lets make the hotkey with the following code.
Code: Select all
  def closeapp(self, widget, event) :
   if event.keyval == gtk.keysyms.Escape :
	gtk.main_quit()
See how easy that is?

So here's the full code for this simple app.
Code: Select all
#!/usr/bin/env python

import gtk

class app:
	
  def closeapp(self, widget, event) :
   if event.keyval == gtk.keysyms.Escape :
	gtk.main_quit()

  def __init__(self):
	window = gtk.Window(gtk.WINDOW_TOPLEVEL)
	window.set_position(gtk.WIN_POS_CENTER)
	window.set_title("TestApp")
	window.set_default_size(320, 200)
	window.connect("destroy", gtk.main_quit)
	window.connect("key-press-event", self.closeapp)
	window.show_all()

app()
gtk.main()
Enjoy!
1 post Page 1 of 1
Return to “Programming”