你可以使用
turtle
模块,如果你不想安装外部模块。我创建了一些有用的函数:
setwindowsize( x,y )
- 将窗口大小设置为 x*y
drawpixel( x, y, (r,g,b), pixelsize)
- 使用 RGB 颜色(元组)和像素大小在 x:y 坐标处绘制像素
showimage()
- 显示图像
import turtle
def setwindowsize(x=640, y=640):
turtle.setup(x, y)
turtle.setworldcoordinates(0,0,x,y)
def drawpixel(x, y, color, pixelsize = 1 ):
turtle.tracer(0, 0)
turtle.colormode(255)
turtle.penup()
turtle.setpos(x*pixelsize,y*pixelsize)
turtle.color(color)
turtle.pendown()
turtle.begin_fill()
for i in range(4):
turtle.forward(pixelsize)
turtle.right(90)
turtle.end_fill()
def showimage():
turtle.hideturtle()
turtle.update()
范例:
200x200 的窗口,中心点有一个红色像素
setwindowsize(200, 200)
drawpixel(100, 100, (255,0,0) )
showimage()
![enter image description here](https://istack.dev59.com/2fV7U.webp)
30x30 随机颜色。像素大小:10
from random import *
setwindowsize(300,300)
for x in range(30):
for y in range(30):
color = (randint(0,255),randint(0,255),randint(0,255))
drawpixel(x,y,color,10)
showimage()
![enter image description here](https://istack.dev59.com/Dlda5.webp)
toimage
函数在 Scipy 1.3.0 版本中已被删除。因此,如果您想使用此解决方案,需要安装1.2.0版本。 - Dogu Deniz Ugur