Luk*_*lor 6 python tkinter function rotation python-2.7
我正在写一个python spirograph程序,我需要一些帮助将它的一部分转换成一个函数.代码试图重现我在这里找到的视频中说明的结果.一条线围绕原点旋转,然后另一条线从其末端旋转,等等.
通过对(我认为是)三角学的一点研究,我把一个函数放在一起rotate(point, angle, center=(0, 0)).用户输入要旋转的点,旋转的角度(顺时针),以及旋转的中心点.
然后,我实施了初始测试,其中一条线围绕另一条线旋转.第二行的结尾绘制就像握笔一样.代码有点乱,但看起来像这样.
x, y = 0, 0
lines = []
while 1:
point1 = rotate((0,50), x)
point2 = map(sum,zip(rotate((0, 50), y), point1))
if x == 0:
oldpoint2 = point2
else:
canvas.create_line(oldpoint2[0], oldpoint2[1], point2[0], point2[1])
lines.append( canvas.create_line(0, 0, point1[0], point1[1]) )
lines.append( canvas.create_line(point1[0], point1[1], point2[0], point2[1]) )
oldpoint2 = point2
tk.update()
x += 5
if x > 360 and y > 360:
x -= 360
canvas.delete("all")
time.sleep(1)
y += 8.8
if y > 360: y -= 360
for line in lines:
canvas.delete(line)
lines = []
Run Code Online (Sandbox Code Playgroud)
很棒,效果很好.然而,我的最终目标是视频中的内容.在视频中,用户可以输入任意数量的手臂,然后定义每个手臂的长度和角速度.我只能用两只手臂工作.最后,我的问题是如何将我发布的代码放入一个看起来像的函数中drawSpiral(arms, lenlist, velocitylist).它需要武器的数量,每个手臂的速度列表,以及每个手臂的长度列表作为参数.
我已经好几次试过这个了.最初,我有一些根本不起作用的东西.我有一些很酷的形状,但绝对不是理想的输出.我已经工作了几个小时,我能得到的最接近的是:
def drawSpiral(arms, lenlist, velocitylist):
if not arms == len(lenlist) == len(velocitylist):
raise ValueError("The lists don't match the provided number of arms")
iteration = 0
while 1:
tk.update()
iteration += 1
#Empty the list of points
pointlist = []
pointlist.append((0, 0))
#Create a list of the final rotation degrees for each point
rotations = []
for vel in velocitylist:
rotations.append(vel*iteration)
for n in range(arms):
point = tuple(map(sum,zip(rotate((0, lenlist[n]), rotations[n], pointlist[n]))))
pointlist.append(point)
for point in pointlist:
create_point(point)
for n in range(arms):
print pointlist[n], pointlist[n+1]
Run Code Online (Sandbox Code Playgroud)
我觉得这与我的解决方案非常接近,但并不完全相同.调用drawSpiral(2, [50, 75], [1, 5])看起来可能会产生一些正确的点,但不会连接正确的集合.盯着它看了一个小时,尝试了几件事,我没有取得任何进展.看着我自己的代码,我也很困惑.我被卡住了!围绕中心旋转的点附着在对角地穿过屏幕并向后飞行的点上.连接到中心的线来回伸展.有人能指出我正确的方向吗?
我已经设置了两个函数来绘制每个臂末端的点,并找到了一些有趣的结果.在两种情况下,第一臂以5的速度旋转,第二臂以-3的速度旋转.函数外部的循环正在生成模式:

调用的函数drawSpiral(2, [50, 50], [5, -3])产生结果
它似乎正在拉伸上半部分.当双臂的速度为5时,预计该功能会产生两个圆,一个比另一个大.然而,它产生一个倒置的心形,其中点连接到中心.
现在有更多的证据,能理解数学的人比我更能帮助我吗?
你的错误是在
for n in range(arms):
point = tuple(map(sum,zip(rotate((0, lenlist[n]), rotations[n], pointlist[n]))))
pointlist.append(point)
Run Code Online (Sandbox Code Playgroud)
具体来说,
rotate((0, lenlist[n])
Run Code Online (Sandbox Code Playgroud)
替换为
for n in range(arms):
point = tuple(map(sum,zip(rotate((pointlist[n][0], lenlist[n]), rotations[n], pointlist[n]))))
pointlist.append(point)
Run Code Online (Sandbox Code Playgroud)
您违反了极坐标(圆形图)的通常数学符号,这导致了您的困惑和最终的问题。据我所知,您的函数正在绘制一个(X,Y)点(0,长度),然后找到该点与中心点(正确定义为您找到的最后一个点)之间的差异并将其旋转那个中心。问题是 (0,length)距离中心的距离不是“ length ”。通过将 (0,lenlist[n]) 替换为 (pointlist[n][0],lenlist[n]) 使下一个点基于上一个点。
另外,我建议将旋转函数编辑为旋转(长度,角度,中心点),这会将输入简化为更传统的表示形式。