How to draw polygons with Python?

前端 未结 6 979
南笙
南笙 2021-02-05 08:38

I have input values of x, y coordinates in the following format:

[[1,1], [2,1], [2,2], [1,2], [0.5,1.5]]

I want to draw polygons, but I don\'t

6条回答
  •  迷失自我
    2021-02-05 08:55

    Also, if you're drawing on window, use this:

    dots = [[1,1], [2,1], [2,2], [1,2], [0.5,1.5]]
    from tkinter import Canvas
    c = Canvas(width=750, height=750)
    c.pack()
    out = []
    for x,y in dots:
        out += [x*250, y*250]
    c.create_polygon(*out, fill='#aaffff')#fill with any color html or name you want, like fill='blue'
    c.update()
    

    or also you may use this:

    dots = [[1,1], [2,1], [2,2], [1,2], [0.5,1.5]]
    out = []
    for x,y in dots:
        out.append([x*250, y*250])
    import pygame, sys
    from pygame.locals import *
    pygame.init()
    DISPLAYSURF = pygame.display.set_mode((750, 750), 0, 32)
    pygame.display.set_caption('WindowName')
    DISPLAYSURF.fill((255,255,255))#< ; \/ - colours
    pygame.draw.polygon(DISPLAYSURF, (0, 255,0), out)
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
        pygame.display.update()
    

    First needs tkinter, second - pygame. First loads faster, second draws faster, if you put DISPLAYSURF.fill and than pygame.draw.polygon with a bit different coordinates into loop, it will work better than the same thing in tkinter. So if your polygon is flying and bouncing around, use second, but if it's just stable thing, use first. Also, in python2 use from Tkinter, not from tkinter. I've checked this code on raspberrypi3, it works.

    ------------EDIT------------

    A little bit more about PIL and PYPLOT methods, see another answers:

    matplotlib uses tkinter, maybe matplotlib is easier-to-use, but it's basically cooler tkinter window.

    PIL in this case uses imagemagick, which is really good image editing tool

    If you also need to apply effects on image, use PIL.

    If you need more difficult math-figures, use matplotlib.pyplot.

    For animation, use pygame.

    For everything you don't know any better way to do something, use tkinter.

    tkinter init is fast. pygame updates are fast. pyplot is just a geometry tool.

提交回复
热议问题