Tkinter Canvas Draw Rectangle
create_rectangle() It is used as follows.
create_rectangle(x1, y1, x2, y2, options)
(x1,y1) and (x2,y2) are the coordinates of the top-left and bottom-right corners of the rectangle. The following are the common uses of options.
(1) dash
: create dashed lines, same as create_line( ).
(2) dashoffset
: Generate dashed line as dash, but the number is the width of the blank at the beginning.
(3) fill
: rectangle fill color.
(4) outline
: set the rectangle line color.
(5) stipple
: draw bitmap rectangle.
(6) width
: width of the rectangle line.
Example#1
Generate random rectangles of different positions and sizes within the canvas.
from tkinter import *
from random import *
tk = Tk()
tk.title("apidemos.com")
canvas = Canvas(tk, width=640, height=480)
canvas.pack()
for i in range(20):
x1, y1 = randint(1,640), randint(1,480)
x2, y2 = randint(1,640), randint(1,480)
if x1 > x2:
x1,x2 = x2,x1
if y1 > y2:
y1,y2 = y2,y1
canvas.create_rectangle(x1,y1,x2,y2)
# canvas.create_line(x1,y1,x2,y2)
tk.mainloop()
Output:
This program produces a different result each time it is executed, with a bit of an artistic painting effect. When using create_rectangle(), you can set the rectangle fill color with fill=’color’ and the rectangle outline color with outline=’color’ in the options parameter field.
Example#2
Draw three rectangles, the first using red fill outline color is the default setting, the second using yellow fill outline is blue, and the third using green fill outline is gray.
from tkinter import *
from random import *
tk = Tk()
tk.title("apidemos.com")
canvas = Canvas(tk, width=640, height=480)
canvas.pack()
canvas.create_rectangle(10,10,120,60,fill="red")
canvas.create_rectangle(130,10,200,80,fill="yellow",outline='blue')
canvas.create_rectangle(210,10,300,60,fill="green",outline='grey')
tk.mainloop()
Output:
From the execution result, we can find that the third rectangle is outlined in gray because the canvas base color is light gray, so the outline line is almost invisible, in addition, you can also set the width of the rectangle outline with width.