如何用Python绘制多边形?

2024-04-24 16:09:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有x,y坐标的输入值,格式如下:

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

我想画多边形,但我不知道怎么画!

谢谢


Tags: 格式多边形
2条回答

另外,如果要在窗口上绘制,请使用以下命令:

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

或者也可以使用:

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

第一个需要tkinter,第二个需要pygame。第一个加载速度更快,第二个绘制速度更快,如果你把DISPLAYSURF.fillpygame.draw.polygon放进一个不同坐标的循环中,它将比tkinter中相同的东西工作得更好。所以,如果你的多边形是飞行和反弹,使用第二,但如果它只是一个稳定的东西,使用第一。另外,在python2中使用from Tkinter,而不是from tkinter。 我已经在raspberrypi3上检查过这个代码,它是有效的。

—————————————————————————

关于PIL和PYPLOT方法的更多信息,请参见其他答案:

matplotlib使用tkinter,也许matplotlib更容易使用,但它基本上是更酷的tkinter窗口。

在本例中,PIL使用了imagemagick,这是一个非常好的图像编辑工具

如果还需要对图像应用效果,请使用PIL

如果需要更难的数学图形,请使用matplotlib.pyplot

对于动画,请使用pygame

对于任何你不知道的更好的方法,使用tkinter

tkinter初始化很快。pygame更新很快。pyplot只是一个几何工具。

另一种绘制多边形的方法是:

import PIL.ImageDraw as ImageDraw
import PIL.Image as Image

image = Image.new("RGB", (640, 480))

draw = ImageDraw.Draw(image)

# points = ((1,1), (2,1), (2,2), (1,2), (0.5,1.5))
points = ((100, 100), (200, 100), (200, 200), (100, 200), (50, 150))
draw.polygon((points), fill=200)

image.show()

请注意,您需要安装枕头库。另外,我把你的坐标放大了100倍,这样我们就能在640x 480屏幕上看到多边形。

希望这有帮助。

相关问题 更多 >