Home > Mobile >  How do I draw a pattern of shapes using the Tkinter Canvas?
How do I draw a pattern of shapes using the Tkinter Canvas?

Time:03-24

Essentially, i have a polygon shape drawn out in my canvas, and want to duplicate it so that it fills up the entire canvas.

I am quite new to programming in general, and thought i could use a for loop but that didn't really work out the way i wanted it to, so i'm curious if anyone could show me how i can achieve this.

The code shows essentially what i want to do, but i don't want to rewrite this 10 times to fill the whole canvas

from tkinter import *
root = Tk()
canvas = Canvas()

points = [125, 100, 225, 100, 225, 100, 250, 150, 250, 150, 100, 150]    

canvas.create_polygon(points, outline = "blue", fill = "orange", width = 2)
canvas.pack()

points = [125, 150, 225, 150, 225, 150, 250, 200, 250, 200, 100, 200]    

canvas.create_polygon(points, outline = "blue", fill = "orange", width = 2)
canvas.pack()

root.mainloop()

CodePudding user response:

First, you only need to pack canvas once.

Then you can use a for loop to move the points for each new polygon. One neat trick is to use zip() which will combine the points with a list of displacements, but only for every other item in the list. Example:

from tkinter import *

root = Tk()
canvas = Canvas()
canvas.pack()

points = [125, 100, 225, 100, 225, 100, 250, 150, 250, 150, 100, 150]    

shift_list = [0, 50, 100, 150]  # values to shift polygon for each repetition

for delta_y in shift_list:
    shifted = []    
    for x, y in zip(points[::2], points[1::2]): # Loop through points
        shifted.append(x)
        shifted.append(y delta_y)
    canvas.create_polygon(shifted, outline="blue", fill="orange", width=2)

root.mainloop()

The line:

for x, y in zip(points[::2], points[1::2])

will take the list points but only every other item points[::2] and combine it with the list points but only every other item starting from the second item points[1::2] which will give the for loop x & y values for each point. This type of technique using zip() is very useful and one you should keep close to your heart.

Then just add a displacement value and plot the polygon.

  • Related