O'Reilly logo

Programming Python, Second Edition by Mark Lutz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Canvas

When it comes to graphics, the Tkinter Canvas widget is the most free-form device in the library. It’s a place to draw shapes, move objects dynamically, and place other kinds of widgets. The canvas is based on a structured graphic object model: everything drawn on a canvas can be processed as an object. You can get down to the pixel-by-pixel level in a canvas, but you can also deal in terms of larger objects like shapes, photos, and embedded widgets.

Basic Canvas Operations

Canvases are ubiquitous in much nontrivial GUI work, and we’ll see larger canvas examples show up later in this book under the names PyDraw, PyView, PyClock, and PyTree. For now, let’s jump right into an example that illustrates the basics. Example 8-13 runs most of the major canvas drawing methods.

Example 8-13. PP2E\Gui\Tour\canvas1.py

# demo all basic canvas interfaces from Tkinter import * canvas = Canvas(width=300, height=300, bg='white') # 0,0 is top left corner canvas.pack(expand=YES, fill=BOTH) # increases down, right canvas.create_line(100, 100, 200, 200) # fromX, fromY, toX, toY canvas.create_line(100, 200, 200, 300) # draw shapes for i in range(1, 20, 2): canvas.create_line(0, i, 50, i) canvas.create_oval(10, 10, 200, 200, width=2, fill='blue') canvas.create_arc(200, 200, 300, 100) canvas.create_rectangle(200, 200, 300, 300, width=5, fill='red') canvas.create_line(0, 300, 150, 150, width=10, fill='green') photo=PhotoImage(file='../gifs/guido.gif') canvas.create_image(250, 0, image=photo, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required