5.3. Graphics

When we want to display 2D graphics or images on the screen, the Canvas object is needed in the application body. Canvas is a UI element that provides a drawable area on the screen but it also provides support for handling keyboard events, as we saw in Section 5.2. We showed how to create a canvas object and how to assign it to the application body. We also mentioned that it has an optional parameter, redraw_callback, that defines a callback function that is called whenever a part of the canvas must be redrawn. Typically, this happens when the user switches away from the Python application and back again or after a popup menu is displayed.

5.3.1. Drawing Graphics Primitives

This section shows you how to draw circles, rectangles, lines and points – that is, all kinds of graphics primitives. A common way to perform drawing and showing graphics on the screen is that you first create a graphics.Image object, manipulate that object and then draw it on the canvas (screen) in the redraw_callback function.

This process is called double buffering. The name refers to the fact that instead of drawing primitives directly on the canvas, which is possible as well, you draw them in a separate image (buffer) first. This way you do not have to draw everything again when the canvas must be redrawn, for example after a popup dialog has cleared a part of the canvas. Instead, you simply copy the image to the canvas. The Image.blit() function that handles the copying is typically accelerated ...

Get Mobile Python: Rapid Prototyping of Applications on the Mobile Platform now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.