Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

python - How to draw a pixel on the screen directly?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Direct answer:

This can only be done with OS-specific APIs. Some OSes do 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...