我如何在 Tkinter 中复制和移动形状 Canvas

How do i duplicate and move a shape in Tkinter Canvas

我知道我过去问过类似的问题,答案很有效,但我无法理解如何在这种特定情况下移动此形状。

基本上这个形状应该是多排的,都是挨着的,再往下排需要稍微偏移,然后来回...

我确实尝试使用 points[::x]points[x::y] 来跳过我不想更改的值,这是我从上一个问题中学到的,但我无法弄清楚如何写代码,以便形状像在图像中那样显示。我也一直在尝试使用 zip() 但是因为我之前从未使用过它,所以它没有按照我想要的方式工作

下面是代码的一部分,详细说明了需要复制的起始形状。

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()

您可以复制和修改 points 中的数据以在不同位置绘制多边形,但在同一位置绘制并获取对象 ID 会更简单

polygon_id = canvas.create_polygon(...)

并将其移动一些偏移量

canvas.move(polygon_id, offset_x, offset_y)

完整的工作代码:

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()

另一个例子 - row_offset:

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()