简体   繁体   中英

Drawing a filled polygon using graphics library

I have to draw an hourglass in PyCharm. I tried the following, but for some reason the setFill command doesn't work. It only works for canvas.drawRect(x, y, width, height). I guess because the program doesn't recognize that the lines are making a triangle and therefore can't fill it.

Does anyone have any idea how I can fix it?

canvas.setFill("blue")
canvas.drawLine(100, 50, 200, 50)
canvas.drawLine(100, 50, 150, 200)
canvas.drawLine(200, 50, 150, 200)

The lines you are tracing do not define a fillable object. You should define objects that support the setFill() method:

from graphics import *

def main():
    win = GraphWin("My Canvas", 300, 300)

    poly_points = [Point(100, 50), Point(200, 50), Point(150, 200)]

    p = Polygon(poly_points)
    p.setFill('red')
    p.draw(win)

    c = Circle(Point(50,50), 10)
    c.setFill('blue')
    c.draw(win)

    win.getMouse() # Pause to view result
    win.close()    # Close window when done

main()

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