Home

A Simple Python Script of Drawing Figures

 

This is a simple script in Python, which paints a rectangle and a circle.

 

from tkinter import *

 

c = Canvas(width = 800, height = 600, background = 'white')

c.pack()

c.create_rectangle(200, 100, 600, 500, outline = 'aqua', fill = 'aqua')

c.create_oval(300, 200, 500, 400, outline = 'blue', width = 10, fill = 'greenyellow')

 

Run this script, then a window of Figure 1 will be shown.

Figure 1

 

The first statement

from tkinter import *

imports Canvas class from tkinter.

 

The following statement

c = Canvas(width = 800, height = 600, background = 'white')

creates a Canvas object, which has width 800pixels, height 600pixels, and background of color white. For the Canvas, the upper left corner is at (0, 0), and the lower right corner is at (800, 600).

 

To show the canvas, the following statement must be executed.

c.pack()

 

The following statement draws a rectangle.

c.create_rectangle(200, 100, 600, 500, outline = 'aqua', fill = 'aqua')

The rectangle has the upper left corner at (200, 100), and the lower right corner at (600, 500). The color of the outline is aqua, and the interior is aqua. When the key fill is not specified, only the outline is drawn.

 

The following statement paints a oval.

c.create_oval(300, 200, 500, 400, outline = 'blue', width = 10, fill = 'greenyellow')

This oval is painted within a rectangle, which has the upper left corner (300, 200), and the lower right corner (500, 400). The outlines width is 10.

 

 

It is easy to display a string.

The following script

from tkinter import *

c = Canvas(width = 500, height = 200, background = 'white')

c.pack()

c.create_text(250, 100, text = 'Hello !', font = ('Times New Roman', 100), fill = 'blue')

will display the text as Figure 2.

Figure 2

 

The center of the string is at (250, 100).

 

Detailed information is available from Python help (Figures 3).

Figure 3

 

The following Python script rotates the disc.

 

from tkinter import *

import time

import math

 

c = Canvas(width = 400, height = 300, background = 'white')

c.pack()

t = 0.0

wh = 100

try:

    while True:

        c.create_rectangle(0, 0, 400, 300, fill = 'white')

        ws = math.fabs(wh * math.cos(t))

        c.create_oval(200 - ws, 50, 200 + ws, 250, fill = '#0000ff')

        c.update()

        time.sleep(0.1)

        t += 0.1

        if (t > math.pi * 2):

            t -= math.pi * 2

except:

    print('Good bye !')

 

Run the above script, then the disc will rotate as shown below:

 

 

Home