Python 3图形(绘制一颗星)

时间:2014-11-16 01:35:09

标签: python python-3.x zelle-graphics

我目前正在使用Python Graphics。 (这与" Python Turtle"不同,您可以通过Google搜索" Python Graphics"来下载网站包。)搜索了一段时间后如何绘制一个星星,我无法找到有关此信息的任何信息。

这是我弄清楚它如何运作的唯一方法:

from graphics import *

def main():
    win = GraphWin('Star', 600, 600)
    win.setCoords(0.0, 0.0, 600.0, 600.0)
    win.setBackground('White')

    p1 = win.getMouse()
    p1.draw(win)
    p2 = win.getMouse()
    p2.draw(win)
    p3 = win.getMouse()
    p3.draw(win)
    p4 = win.getMouse()
    p4.draw(win)
    p5 = win.getMouse()
    p5.draw(win)
    p6 = win.getMouse()
    p6.draw(win)
    p7 = win.getMouse()
    p7.draw(win)
    p8 = win.getMouse()
    p8.draw(win)
    p9 = win.getMouse()
    p9.draw(win)
    p10 = win.getMouse()
    p10.draw(win)
    vertices = [p1, p2, p3, p4, p5, p6, p7, p8, p9, p10]
    print(vertices.getPoints())

    # Use Polygon object to draw the star
    star = Polygon(vertices)
    star.setFill('darkgreen')
    star.setOutline('darkgreen')
    star.setWidth(4)  # width of boundary line
    star.draw(win)

main()

这可行,但不太好,因为我无法获得一个完美的明星,我总是猜测我在哪里点击。

1 个答案:

答案 0 :(得分:0)

以下是基于code for drawing a star in C#解决此问题的数学方法:

import math
from graphics import *

POINTS = 5
WIDTH, HEIGHT = 600, 600

def main():
    win = GraphWin('Star', WIDTH, HEIGHT)
    win.setCoords(-WIDTH/2, -HEIGHT/2, WIDTH/2, HEIGHT/2)
    win.setBackground('White')

    vertices = []

    length = min(WIDTH, HEIGHT) / 2

    theta = -math.pi / 2
    delta = 4 / POINTS * math.pi

    for _ in range(POINTS):
        vertices.append(Point(length * math.cos(theta), length * math.sin(theta)))
        theta += delta

    # Use Polygon object to draw the star
    star = Polygon(vertices)
    star.setFill('darkgreen')
    star.setOutline('lightgreen')
    star.setWidth(4)  # width of boundary line
    star.draw(win)

    win.getMouse()
    win.close()

main()

请注意,我更改了坐标系以简化解决方案。

此外,填充在某些系统上可能看起来很奇怪,例如Unix(中心未填充),但看起来完全填满其他系统,如Windows。这是在Tkinter库中实现fill的方式的工件,它支撑着Zelle图形:

enter image description here

你可以通过计算沿着外围的点而不仅仅是星的(交叉)点来完全填充它。