简体   繁体   中英

Python 3 Graphics (Drawing a star)

I am currently using Python Graphics. (This is not the same as "Python Turtle", you can download the site package via a google search of "Python Graphics".) After searching for a while on how to draw a star, I couldn't find any information on this.

This is the only way I have figured out how it would work:

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()

This works but not too well as I can't get a perfect star and I always have to guess where I am clicking.

Below is a mathematical approach to solving this problem based on 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()

Note that I changed the coordinate system to simplify the solution.

Also, the fill may look strange on some systems like Unix (unfilled in the center) but look completely filled other systems, like Windows. This is an artifact of the way fill is implemented in the Tkinter library that underpins Zelle graphics:

在此处输入图片说明

You can probably make it fill completely in both by calculating the points along the outer perimeter rather than just the (crossing) points of the star.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM