从Turtle到Tkinter的翻译,画出摩洛哥马赛克的

时间:2019-06-27 06:47:21

标签: tkinter drawing tkinter-canvas

我想重现here所见的美丽的摩洛哥马赛克。该代码正在使用Turtle。我想将其翻译为Tkinter。我很幸运地修改了答案here中的代码以绘制到画布上。当然,由于没有从原点绘制任何线,因此缺少很多东西。我不知道该怎么做。一个想法是,我可能会覆盖n个多边形,尽管每个多边形旋转了2 * pi / n度。这仍然留下了将线从原点到每个多边形的起点和终点的问题。我认为这并不能解决所有问题,但这是一个很好的开始。

enter image description here

或者也许更简单地使多边形围绕中心旋转?

from tkinter import *
import math
canvas_width = 400
canvas_height =400
python_green = "#476042"

def polygon(canvas,sides=10, radius=100, rotation=0, translation=None, outline=python_green, fill='White', width = 1):
   one_segment = math.pi * 2 / sides
   points = [
       (math.sin(one_segment * i + rotation) * radius + canvas_width/2,
        math.cos(one_segment * i + rotation) * radius + canvas_height/2)
       for i in range(sides)]

   if translation:
       points = [[sum(pair) for pair in zip(point, translation)]
                 for point in points]


   canvas.create_polygon(points, outline=outline, fill='', width=width)

master = Tk()
w = Canvas(master, width=canvas_width, height=canvas_height)
w.pack()
polygon(w,outline='green', width=2)

mainloop()

1 个答案:

答案 0 :(得分:0)

您可以使用相同的代码,而无需将其“翻译”为tkinter-您所需要做的就是创建一个canvas,然后使用RawTurtle直接在canvas上绘制

import turtle
import tkinter as tk

root = tk.Tk()
canvas = tk.Canvas(root,width=600,height=600)
canvas.pack()

#below code same from the linked source
myPen = turtle.RawTurtle(canvas) #changed from turtle.Turtle()
myPen.shape("arrow")
myPen.speed(1000)

def drawMosaic(color1, numberOfSides1, size1, color2, numberOfSides2, size2, numberOfIterations):
    for i in range(0, numberOfIterations):
        myPen.color(color1)
        for j in range(0, numberOfSides1):
            myPen.forward(size1)
            myPen.left(360 / numberOfSides1)
        myPen.color(color2)
        for k in range(0, numberOfSides2):
            myPen.forward(size2)
            myPen.left(360 / numberOfSides2)

        myPen.left(360 / numberOfIterations)

drawMosaic("#980C6B", 8, 80, "#DD6BB8", 5, 70, 20)

root.mainloop()