-
Book Overview & Buying
-
Table Of Contents
Python Game Programming By Example
By :
So far, we have the window set up and now we can start drawing items on the canvas. The Canvas widget is two-dimensional and uses the Cartesian coordinate system. The origin—the (0, 0) ordered pair—is placed in the top-left corner, and the axis can be represented as shown in the following screenshot:

Keeping this layout in mind, we can use two methods of the Canvas widget to draw the paddle, the bricks, and the ball:
canvas.create_rectangle(x0, y0, x1, y1, **options)canvas.create_oval(x0, y0, x1, y1, **options)Each of these calls returns an integer, which identifies the item handle. This reference will be used later to manipulate the position of the item and its options. The **options syntax represents a key/value pair of additional arguments that can be passed to the method call. In our case, we will use the fill and the tags option.
The x0 and y0 coordinates indicate the top-left corner of the previous screenshot, and x1 and y1 are indicated in the bottom-right corner.
For instance, we can call canvas.create_rectangle(250, 300, 330, 320, fill='blue', tags='paddle') to create a player's paddle, where:
fill='blue' means that the background color of the item is blue.tags='paddle' means that the item is tagged as a paddle. This string will be useful later to find items in the canvas with specific tags.We will invoke other Canvas methods to manipulate the items and retrieve widget information. This table gives the references to the Canvas widget that will be used in this chapter:
|
Method |
Description |
|---|---|
|
|
Returns the coordinates of the bounding box of an item. |
|
|
Moves an item by a horizontal and a vertical offset. |
|
|
Deletes an item from the canvas. |
|
|
Retrieves the canvas width. |
|
|
Changes the options of an item, such as the fill color or its tags. |
|
|
Binds an input event with the execution of a function. The callback handler receives one parameter of the type Tkinter event. |
|
|
Unbinds the input event so that there is no callback function executed when the event occurs. |
|
|
Draws text on the canvas. The |
|
|
Returns the items with a specific tag. |
|
|
Returns the items that overlap or are completely enclosed by a given rectangle. |
You can check out a complete reference of the event syntax as well as some practical examples at http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm#events.
Change the font size
Change margin width
Change background colour