我正试图用tkinter绘制出一个斐波纳契向日葵。它绘制正确,但我希望能够绘制螺旋。但是,我无法弄清楚如何正确连接它们。有什么想法吗?
这是我的代码:
import math
from tkinter import *
def s5(n,r): #works better for first direction
spirals = []
for i in range(n+1):
spirals.append(((r*(i**0.5),((i*(360)/(((5**0.5)+1)/2))%360))))
return spirals
# convert to cartesian to plot
def pol2cart(r,theta):
x = r * math.cos(math.radians(theta))
y = r * math.sin(math.radians(theta))
return x,y
# set size of fib sun
num_points = 200
distance = 15
# do the cartesian conversion
coordinates = [pol2cart(r,t) for r,t in s5(num_points,distance)]
# center for the canvas
coordinates = [(x+250,y+250) for x,y in coordinates]
# create gui
master = Tk()
canvas = Canvas(master,width = 500,height=500)
canvas.pack()
# plot points
h= 1
for x,y in coordinates:
canvas.create_oval(x+7,y+7,x-7,y-7)
canvas.create_text(x,y,text=h)
h += 1
mainloop()
这是我想要实现的结果:
答案 0 :(得分:4)
这是一个有趣的问题,我刚刚勾画出一个可能的解决方案。您可以从1到20开始,然后将每个数字添加到21。意思是你应该连接1到22,22到43,43到64,...... 再次连接2到23,23到44,......
这为您提供了一个方向的踏板。
对于另一个方向,您可以执行相同的操作,但从1到34开始,并为每个数字添加34。意思是从1开始并向其添加34。 1,35,69,...... 2,36,70,...
这两个图显示了这些螺旋的外观:
事实上这些数字并不神奇,这些数字来自斐波那契数字,并且基于螺旋层,您应该检测它。因此,您总是有数字差异,如:0,1,1,2,3,5,8,13,21,34,55 ......
答案 1 :(得分:2)
你的程序的以下版本实际上绘制了线条,但我还没有找到21和34步骤的动机。我怀疑这与你在s5函数中使用的数字有关('5')。
import math
from Tkinter import *
class Fibonacci():
def s5(self, n, r): # works better for first direction
spirals = []
for i in range(n+1):
spirals.append(((r*(i**0.5),((i*(360)/(((5**0.5)+1)/2))%360))))
return spirals
def pol2cart(self, r, theta):
x = r * math.cos(math.radians(theta))
y = r * math.sin(math.radians(theta))
return x,y
def calculate_coordinates(self, num_points = 200, distance = 15):
# do the cartesian conversion
self.coordinates = [self.pol2cart(r, t) for r, t in self.s5(num_points, distance)]
# center for the canvas
self.coordinates = [(x+250,y+250) for x, y in self.coordinates]
def plot_numbers(self, canvas):
h = 1
self.calculate_coordinates(num_points = 200, distance = 15)
for x, y in self.coordinates:
canvas.create_oval(x+7, y+7, x-7, y-7)
canvas.create_text(x, y, text = h)
h += 1
def plot_lines(self, canvas):
for delta in [21, 34]:
for start in range(34):
x0, y0 = self.coordinates[0]
i = start
while i < len(self.coordinates):
x1, y1 = self.coordinates[i]
canvas.create_line(x0, y0, x1, y1)
x0 = x1; y0 = y1
i += delta
def create_gui(self):
master = Tk()
canvas = Canvas(master, width = 500, height = 500)
canvas.pack()
self.plot_numbers(canvas)
self.plot_lines(canvas)
mainloop()
def main():
f = Fibonacci()
f.create_gui()
return 0
if __name__ == '__main__':
main()
要消除中心作为起点,请修改plot_lines,如下所示:
def plot_lines(self, canvas):
for delta in [21, 34]:
for start in range(34):
x0, y0 = self.coordinates[start]
print x0, y0
i = start + delta
while i < len(self.coordinates):
x1, y1 = self.coordinates[i]
canvas.create_line(x0, y0, x1, y1)
x0 = x1; y0 = y1
i += delta
这给出: