Home > Blockchain >  How do i duplicate and move a shape in Tkinter Canvas
How do i duplicate and move a shape in Tkinter Canvas

Time:04-05

I am aware that I have asked a similar question in the past, and the answer worked great, but I just cant get my head around how to move this shape in this specific case.

Essentially there should be multiple rows of this shape, all next to each-other, and the next row down needs to be slightly offset, and then back and forth...

Here is an image of what I have been trying to achieve

I did try using points[::x] and points[x::y] to skip the values i didn't want changed, which is what I learnt from my previous question, but I cant figure out exactly how to write the code so that the shapes display as they do in the image. I have also been trying to use zip() but since I have never used it before it did not work the way I wanted it to

Below is a part of the code detailing the starting shape which needs to be duplicated.

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

points = [5, 10, 15, 5, 15, 5, 25, 5, 25, 5, 35, 10, 35, 10, 25, 20, 25, 20, 15, 20]
canvas.create_polygon(points, outline="white", fill="black", width=2)

root.mainloop()

CodePudding user response:

You could duplicate and modify data in points to draw polygons in different places but it can be simpler to draw in the same place and get object ID

polygon_id = canvas.create_polygon(...)

and move it by some offset

canvas.move(polygon_id, offset_x, offset_y)

Full working code:

enter image description here

import tkinter as tk  # PEP8: `import *` is not preferred

root = tk.Tk()

canvas = tk.Canvas()
canvas.pack()

points = [5, 10, 15, 5, 15, 5, 25, 5, 25, 5, 35, 10, 35, 10, 25, 20, 25, 20, 15, 20]

for offset_y in range(0, 300, 30):
    for offset_x in range(0, 300, 30):
        polygon_id = canvas.create_polygon(points, outline="white", fill="black", width=2)
        canvas.move(polygon_id, offset_x, offset_y)

root.mainloop()

Another example - with row_offset:

enter image description here

import tkinter as tk  # PEP8: `import *` is not preferred

root = tk.Tk()

canvas = tk.Canvas()
canvas.pack()

points = [5, 10, 15, 5, 15, 5, 25, 5, 25, 5, 35, 10, 35, 10, 25, 20, 25, 20, 15, 20]

row_offset = 15 

for offset_y in range(0, 300, 15):
    for offset_x in range(0, 360, 30):
        polygon_id = canvas.create_polygon(points, outline="white", fill="black", width=2)
        canvas.move(polygon_id, offset_x row_offset, offset_y)
        
    if row_offset == 15:
        row_offset = 0
    else:
        row_offset = 15

root.mainloop()
  • Related