Python 2.6 Graphics Cookbook
上QQ阅读APP看书,第一时间看更新

A circle from an oval

The best way to draw a circle is to use the Tkinter's create_oval() method from the canvas widget.

How to do it...

The instructions used in the first recipe should be used.

Just use the name circle_1.py when you write, save, and execute this program.

#circle_1.py
#>>>>>>>>>>>>>>
from Tkinter import *
root = Tk()
root.title('A circle')

cw = 150                                      # canvas width
ch = 140                                      # canvas height
canvas_1 = Canvas(root, width=cw, height=ch, background="white")
canvas_1.grid(row=0, column=1)                              

# specify bottom-left and top-right as a set of four numbers named # 'xy'
xy = 20, 20, 120, 120         

canvas_1.create_oval(xy)
root.mainloop()

How it works...

The results are given in the next screenshot, showing a basic circle.

How it works...

A circle is just an ellipse whose height and width are equal. In the example here, we have created a circle with the a very compact-looking statement: canvas_1.create_oval(xy).

The compactness comes from the trick of specifying the dimension attributes as a Python tuple xy = 20, 20, 420, 420 . It actually would be better in other instances to use a list such as xy = [ 20, 20, 420, 420 ] because a list allows you to alter the value of the individual member variables, whereas a tuple is an unchangeable sequence of constant values. Tuples are referred to as immutable.

There's more...

Drawing a circle as a special case of an oval is definitely the best way to draw circles. An inexperienced user of Tkinter may be tempted into using an arc to do the job. This is a mistake because as shown in the next recipe the behavior of the create_arc() method does not allow an unblemished circle to be drawn.