- Python 2.6 Graphics Cookbook
- Mike Ohlson de Fine
- 275字
- 2021-04-09 22:39:36
Draw three concentric squares by changing the numerical values defining its position, shape, and color variables.
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() #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
The results are given in the next screenshot.
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.