python绘制像素图_在Python中,如何直接在屏幕上绘制像素?

I'm wanting to do something like the following:

...

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.

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

解决方案

Direct answer:

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

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.

Right answer:

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.

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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值