This demonstration will show how to create a rectangle using the
canvas method in Tkinter.
canvas Method to Create a Basic Example of Rectangle in Tkinter
Each rectangle is defined as (x1, y1) in the upper left corner and (x2, y2) in the pixel area in the lower right corner.
For example, the rectangle upper left corner (100,100) and the lower right corner (102,102) are squares of two pixels by two pixels, including pixels (101,101) but excluding (102,102). Canvas could be used to create multiple shapes.
from tkinter import * # Initialize a window root= Tk() root.geometry('350x250') # Create an instance of a canvas _canvas = Canvas(root,height=200,width=200) _canvas.pack() # create rectangle _canvas.create_rectangle(50, 50, 180, 120,outline="black",fill="blue") root.mainloop()
The Python Tkinter Canvas has built-in methods for creating objects or shapes. We shall use the
create_rectangle() method to create a rectangle.
create_rectangle() method accepts four points x1, y1, x2, y2. Here x1 and y1 are for the upper left corner, and x2 and y2 are for the lower right corner.
Tkinter Rectangle Options
||This option is a tuple of integers. The first number helps for creating pixels that will be drawn. The second number helps for skipping pixels that will be skipped before we start drawing again, and so on. When all the numbers in the tuple are finished, they are reused similarly until the border ends.|
# create dashed border _canvas.create_rectangle(50, 50, 180, 120,outline="black",fill="blue",dash=(4,6))
Now we can see where the borderline is created by 4 pixels after skipping 6 pixels.
||By default, the
_canvas.create_rectangle(50, 50, 180, 120,activefill='blue')
_canvas.create_rectangle(50, 50, 180, 120,state=DISABLED,activefill='blue')
# Create a pattern _canvas.create_rectangle(50, 50, 180, 120,stipple='gray25',fill='black',outline="")
We can increase the width using the
_canvas.create_rectangle(10, 10, 150, 100, fill='blue',width=5)
There are several options in the