Here we are providing an exciting tutorial in Tkinter on how to create a random rectangles generator in a Tkinter.

Sample code

The following Tkinter code will demonstrate the same:

from tkinter import *
import random

root = Tk()
canvas = Canvas(root, width=300, height=300)

def randomRects(num):
    for i in range(0,num):
        x1 = random.randrange(150)
        y1 = random.randrange(150)
        x2 = x1 + random.randrange(150)
        y2 = y1 + random.randrange(150)



In the above code, a method is created called as randomRects, in its definition, a for loop is created from 0 to num, num is the number of rectangles you want to create. It will be passed at the time of calling randomRects. Under the for-loop definition, all co-oordinates of the rectangle are randomly generated using the random method which is imported with the help of line import random, at last create_rectangle is executed to create a rectangle.