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

Draw concentric squares

Draw three concentric squares by changing the numerical values defining its position, shape, and color variables.

How to do it...

The instructions used in recipe 1 should be used.

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

# 3concentric_squares.py
#>>>>>>>>>>>>>>>>>
from Tkinter import *
root = Tk()
root.title('Concentric squares')

cw = 200                                      # canvas width
ch = 400                                      # canvas height
canvas_1 = Canvas(root, width=cw, height=200, background="green")
canvas_1.grid(row=0, column=1)

# dark blue
x_center=  100
y_center=  100
x_width=  100
y_height= 100
kula= "darkblue"
canvas_1.create_rectangle( x_center - x_width/2, \ 
  y_center -  y_height/2,\
  x_center + x_width/2,  y_center + y_height/2, fill=kula)

#dark red
x_width=  80
y_height= 80
kula ="darkred"
canvas_1.create_rectangle( x_center - x_width/2, \ 
  y_center - y_height/2,\
  x_center + x_width/2,  y_center + y_height/2, fill=kula)

#dark green
x_width=  60
y_height= 60
kula ="darkgreen"
canvas_1.create_rectangle( x_center - x_width/2, \ 
  y_center - y_height/2,\
  x_center + x_width/2,  y_center + y_height/2, fill=kula)
root.mainloop()
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

How it works...

The results are given in the next screenshot.

How it works...

In this recipe, we have specified where we want the geometric center of the rectangles located. This is at the position [x_center, y_center] in each instance. You need to do this whenever you want to draw shapes that are concentric. Generally it is always awkward to try and position the center of some drawn figure by manipulating the bottom-right corner. It does of course mean that there is a small amount of arithmetic in calculating where the bottom-left and top-right corners of the bounding box are but this is a small price to pay for the artistic freedom you gain. You only have to use this technique once and it is at your beck and call forever.