To render any sort of graphics from the console, we first need to point pygame to the underlying framebuffer used by Linux.  This is probably the most error-prone operation, but the following code should handle this gracefully and report any errors if something does go wrong.

Enter the following code into your new project, and save the file via the 'Save' button in the top-menu, or just enter CTRL+S:
import os
import pygame
import time
import random

class pyscope :
    screen = None;
    
    def __init__(self):
        "Ininitializes a new pygame screen using the framebuffer"
        # Based on "Python GUI in Linux frame buffer"
        # http://www.karoltomala.com/blog/?p=679
        disp_no = os.getenv("DISPLAY")
        if disp_no:
            print "I'm running under X display = {0}".format(disp_no)
        
        # Check which frame buffer drivers are available
        # Start with fbcon since directfb hangs with composite output
        drivers = ['fbcon', 'directfb', 'svgalib']
        found = False
        for driver in drivers:
            # Make sure that SDL_VIDEODRIVER is set
            if not os.getenv('SDL_VIDEODRIVER'):
                os.putenv('SDL_VIDEODRIVER', driver)
            try:
                pygame.display.init()
            except pygame.error:
                print 'Driver: {0} failed.'.format(driver)
                continue
            found = True
            break
    
        if not found:
            raise Exception('No suitable video driver found!')
        
        size = (pygame.display.Info().current_w, pygame.display.Info().current_h)
        print "Framebuffer size: %d x %d" % (size[0], size[1])
        self.screen = pygame.display.set_mode(size, pygame.FULLSCREEN)
        # Clear the screen to start
        self.screen.fill((0, 0, 0))        
        # Initialise font support
        pygame.font.init()
        # Render the screen
        pygame.display.update()

    def __del__(self):
        "Destructor to make sure pygame shuts down, etc."

    def test(self):
        # Fill the screen with red (255, 0, 0)
        red = (255, 0, 0)
        self.screen.fill(red)
        # Update the display
        pygame.display.update()

# Create an instance of the PyScope class
scope = pyscope()
scope.test()
time.sleep(10)

Huh ... What is all this?

Don't worry if you don't understand every little bit of the code above.  We've provided the code in a way that you simply need to create a new instance of the 'pyscope' class, and the low-level framebuffer implementation should be taken care of.  How do you know it works?  Let's try it out!

There are three lines of code at the bottom that are important:
# Create an instance of the PyScope class
scope = pyscope()
scope.test()
time.sleep(10)
The first line (after the comment) instantiates a new pyscope object named scope.  As soon as this line is executed, the framebuffer will be configured, or any eventual error messages will be displayed if there were any problems.

The second line simply calls a function named 'test' that is in the example code we entered earlier.  This will simply fill the screen with the color red.

The third line causes the program to sleep for 10 seconds before exiting.  This is provided simply to give us a brief delay before the display returns to the shell, restoring whatever was displayed before this program was run.

How Do I Run It?

If you've already run off and clicked the 'Run' button, you might have noticed the following error:
You get this error because the application tries to access the framebuffer using first fbcon, then directfb if that fails and finally svgalib.  They all fail for one important reason:
You need root access to modify the framebuffer!
Future versions of the WebIDE will add the ability to run as root, but if you're running an older version that doesn't already include this functionality, there's an easy workaround.  To give your program access to the framebuffer, simple click the Terminal icon at the top of the text editor, and from the shell that pops up enter:
sudo python pyscope.py
If all goes well, you should see something like the following in your terminal window:
And during 10 seconds, your display should look something like this:

This guide was first published on Oct 19, 2012. It was last updated on Oct 19, 2012.

This page (Pointing Pygame to the Framebuffer) was last updated on Oct 18, 2012.

Text editor powered by tinymce.