April 23, 2014
 
 
RSSRSS feed

PythonGTK Programming part 3: Screensaver, Objects, and User Input

The Fullscreen Function

  • June 10, 2009
  • By Akkana Peck

Expanding on the previous article's screensaver application, today's article will show you how to improve the code in three ways:

  1. Make your window full-screen, so it really looks like a screen saver
  2. Handle keyboard events
  3. Make the code more object-oriented

colors!
colors!

 

Make the window fullscreen

All through the last article I used the term "screensaver" because this sort of whizzy graphics looks kind of like something you'd see in a screensaver application. Well, except for one thing: screensavers cover the whole screen, not just a little window. How can you make your PyGTK application do that?

That's easy: the fullscreen() function. Call it right after you've created the main window:

# Create the main window:
win = gtk.Window()
win.fullscreen()

But when you make the window that big (Figure 1), you start noticing a problem: that big button at the bottom looks silly. You could make it smaller; but why not remove it entirely, and use keyboard events to tell the program when to exit?

 

Handling events

Handling events in PyGTK requires an event handler, similar to the expose and click handlers you've already seen. Here's a simple key handler that exits the program if the user types 'q':

# Called whenever any key is pressed:
def key_press_event(widget, event) :
if event.string == "q" :
gtk.main_quit()

Then register that handler for key events, in the same place you put the fullscreen() call:

# Create the main window:
win = gtk.Window()
win.fullscreen()

# Handle key events
win.connect("key-press-event", key_press_event)

Try it. Don't remove that button yet, until you're sure your key binding is working -- otherwise you'll have no way of quitting the program! But once it's working, you can that ugly button and all the code that handles it, including the click_handler() function at the beginning of the program.

Of course, you can handle other keys besides "q", if you want to do something different depending on what the user types. For instance, you could jump out of fullscreen mode when the user types f:

# Called whenever any key is pressed:
def key_press_event(widget, event) :
if event.string == "q" :
gtk.main_quit()
elif event.string == "f" :
widget.window.unfullscreen()

Unfortunately, PyGTK doesn't give you any way to test whether a window is in fullscreen mode, so you'd have to add another global variable and keep track of it yourself if you want to toggle back and forth between fullscreen and non-fullscreen mode.

Sitemap | Contact Us