本質上,我在畫布中繪制了一個多邊形形狀,并且想要復制它以填滿整個畫布。
一般來說,我對編程很陌生,并認為我可以使用 for 回圈,但這并沒有真正達到我想要的方式,所以我很好奇是否有人可以告訴我如何實作這一點。
代碼基本上顯示了我想要做的事情,但我不想重寫這 10 次來填充整個畫布
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()
uj5u.com熱心網友回復:
首先,您只需要打包一次畫布。
然后,您可以使用 for 回圈來移動每個新多邊形的點。一個巧妙的技巧是使用zip()它將點與位移串列結合起來,但僅適用于串列中的每個其他專案。例子:
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()
該行:
for x, y in zip(points[::2], points[1::2])
將獲取串列點,但僅獲取其他所有專案points[::2],并將其與串列點合并,但僅從第二項開始的所有其他專案合并,points[1::2]這將為每個點提供 for 回圈 x 和 y 值。這種技術zip()非常有用,你應該貼近你的心。
然后只需添加一個位移值并繪制多邊形。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/448496.html
