在Python中,如何直接在屏幕上绘制像素? [英] In Python, how can I draw to a pixel on the screen directly?

查看:1676
本文介绍了在Python中,如何直接在屏幕上绘制像素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做以下事情:

...
pixel[0,0] = [ 254, 0, 0 ] # Draw R at pixel x0y0
pixel[2,1] = [ 0, 254, 0 ] # Draw G at pixel x2y1
pixel[4,2] = [ 0, 0, 254 ] # Draw B at pixel x4y2
...

我希望在短时间内显示许多不同的像素和颜色配置-写入中间文件会太昂贵.

I hope to display many different configurations of pixels and colours in a short space of time -- writing to an intermediary file would be too expensive.

我该如何最好地在Python中实现这一目标?

How should I best go about achieving this goal in Python?

推荐答案

直接回答:

这只能通过特定于操作系统的API来完成.某些操作系统不允许直接更改屏幕上的像素.

This can only be done with OS-specific APIs. Some OSes does not allow changing pixels on the screen directly.

在Windows上,您可以使用 pywin32 库通过dc = GetDC(0)调用获取屏幕的设备上下文,然后用SetPixel(dc, x, y, color)绘制像素.

On Windows, you can use pywin32 libraries to get screen's device context with dc = GetDC(0) call, then paint pixels with SetPixel(dc, x, y, color).

import win32gui
import win32api

dc = win32gui.GetDC(0)
red = win32api.RGB(255, 0, 0)
win32gui.SetPixel(dc, 0, 0, red)  # draw red at 0,0

当然,以这种方式绘制的内容可以随时删除.

Of course, what you paint this way can be erased at any moment.

正确答案:

逐像素绘制是最慢的绘制方法.例如,在Windows上,在内存中创建图像然后执行一次操作绘制的速度比使用SetPixel绘制的速度快了几个数量级.

Painting pixel by pixel is the slowest way to paint something. For example, on Windows, creating an image in memory then painting it in one operation is order of magnitude faster than painting with SetPixel.

如果需要速度,请为python使用一些用户界面库,例如Tkinter模块或PyQt.在内存中创建一个窗口和图像,然后在窗口上绘制图像.如果需要操纵像素,请在图像中操纵它们并每次重新粉刷.

If you need speed, use some user interface library for python, for example, Tkinter module or PyQt. Create a window and image in memory, then paint the image on the window. If you need to manipulate pixels, manipulate them in the image and repaint every time.

这篇关于在Python中,如何直接在屏幕上绘制像素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆