'How do I draw a pattern of shapes using the Tkinter Canvas?
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
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | figbeam |