How to draw a pixel on the screen directly in Python?
Drawing pixels directly on the screen can be a challenging task, especially when it comes to programming. This is because the screen is an abstraction created by the operating system, and most programming languages don’t provide a direct way to access the screen’s memory. However, there are libraries and methods that can be used to accomplish this task in Python.
Method 1: Pygame Library
To draw a pixel on the screen directly using Pygame Library, you can follow these steps:
width, height = 640, 480 screen = pygame.display.set_mode((width, height))
color = (255, 255, 255) # white
x, y = 320, 240 # coordinates of the pixel pygame.draw.rect(screen, color, (x, y, 1, 1))
Here is the complete code:
import pygame pygame.init() width, height = 640, 480 screen = pygame.display.set_mode((width, height)) color = (255, 255, 255) # white x, y = 320, 240 # coordinates of the pixel pygame.draw.rect(screen, color, (x, y, 1, 1)) pygame.display.update()
This code will draw a white pixel at the center of the screen. You can change the color and the coordinates of the pixel to draw it at any location on the screen.
Method 2: Pyglet Library
To draw a pixel on the screen directly using Pyglet, you can follow these steps:
import pyglet from pyglet.gl import *
window = pyglet.window.Window()
glClearColor(1, 1, 1, 1) glClear(GL_COLOR_BUFFER_BIT) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0, window.width, 0, window.height, -1, 1) glMatrixMode(GL_MODELVIEW)
glPointSize(1) glBegin(GL_POINTS) glColor3f(0, 0, 0) # Set the color to black glVertex2i(x, y) # Set the position of the pixel glEnd()
Here’s an example code that draws a pixel at the center of the window:
import pyglet from pyglet.gl import * window = pyglet.window.Window() @window.event def on_draw(): glClearColor(1, 1, 1, 1) glClear(GL_COLOR_BUFFER_BIT) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0, window.width, 0, window.height, -1, 1) glMatrixMode(GL_MODELVIEW) x, y = window.width // 2, window.height // 2 glPointSize(1) glBegin(GL_POINTS) glColor3f(0, 0, 0) glVertex2i(x, y) glEnd() pyglet.app.run()
This code creates a window and draws a black pixel at the center of the window. The on_draw function is called every time the window needs to be redrawn. The glClearColor function sets the background color to white, and the glClear function clears the color buffer. The glMatrixMode function sets the current matrix mode, and the glLoadIdentity function sets the current matrix to the identity matrix. The glOrtho function sets up an orthographic projection, and the glMatrixMode function sets the current matrix mode back to GL_MODELVIEW . The glPointSize function sets the size of the point, and the glBegin and glEnd functions delimit the vertices of the primitive being drawn. The glColor3f function sets the color of the primitive, and the glVertex2i function sets the position of the vertex.
Method 3: PyOpenGL Library
To draw a pixel on the screen directly using the PyOpenGL library, you need to follow these steps:
from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import *
glutInit() glutInitDisplayMode(GLUT_RGBA) glutInitWindowSize(640, 480) glutInitWindowPosition(0, 0) window = glutCreateWindow("Draw Pixel")
glViewport(0, 0, 640, 480) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluOrtho2D(0, 640, 0, 480) glMatrixMode(GL_MODELVIEW)
def draw_pixel(x, y): glBegin(GL_POINTS) glVertex2f(x, y) glEnd()
glClear(GL_COLOR_BUFFER_BIT) glLoadIdentity() draw_pixel(320, 240) glutSwapBuffers()
The above code will draw a pixel at the center of the window.
Here is the complete code with comments:
from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * glutInit() glutInitDisplayMode(GLUT_RGBA) glutInitWindowSize(640, 480) glutInitWindowPosition(0, 0) window = glutCreateWindow("Draw Pixel") glViewport(0, 0, 640, 480) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluOrtho2D(0, 640, 0, 480) glMatrixMode(GL_MODELVIEW) def draw_pixel(x, y): glBegin(GL_POINTS) glVertex2f(x, y) glEnd() glClear(GL_COLOR_BUFFER_BIT) glLoadIdentity() draw_pixel(320, 240) glutSwapBuffers()
This code will draw a single pixel at the center of the window. You can modify the draw_pixel function to draw multiple pixels at different locations. Additionally, you can use other PyOpenGL functions to draw lines, circles, and other shapes.
Method 4: Tkinter Library
To draw a pixel on the screen directly with Tkinter Library in Python, you can use the create_rectangle() method of the Canvas widget. Here is an example code:
from tkinter import * root = Tk() canvas = Canvas(root, width=400, height=400) canvas.pack() canvas.create_rectangle(50, 50, 51, 51, fill="red") canvas.create_rectangle(100, 100, 101, 101, fill="blue") canvas.create_rectangle(200, 200, 201, 201, fill="green") root.mainloop()
In this code, we first create a window and a canvas. Then we use the create_rectangle() method of the canvas to draw pixels on it. The method takes four arguments: the x and y coordinates of the top-left corner of the rectangle, and the x and y coordinates of the bottom-right corner of the rectangle. We set the width and height of the rectangle to 1 pixel to draw a single pixel. Finally, we set the color of the pixel using the fill parameter.
By calling the mainloop() method of the window object, the window will be displayed and the pixels will be drawn on the canvas.
turtle — Turtle graphics¶
Turtle graphics is a popular way for introducing programming to kids. It was part of the original Logo programming language developed by Wally Feurzeig, Seymour Papert and Cynthia Solomon in 1967.
Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an import turtle , give it the command turtle.forward(15) , and it moves (on-screen!) 15 pixels in the direction it is facing, drawing a line as it moves. Give it the command turtle.right(25) , and it rotates in-place 25 degrees clockwise.
Turtle can draw intricate shapes using programs that repeat simple moves.
from turtle import * color('red', 'yellow') begin_fill() while True: forward(200) left(170) if abs(pos()) 1: break end_fill() done()
By combining together these and similar commands, intricate shapes and pictures can easily be drawn.
The turtle module is an extended reimplementation of the same-named module from the Python standard distribution up to version Python 2.5.
It tries to keep the merits of the old turtle module and to be (nearly) 100% compatible with it. This means in the first place to enable the learning programmer to use all the commands, classes and methods interactively when using the module from within IDLE run with the -n switch.
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
The object-oriented interface uses essentially two+two classes:
- The TurtleScreen class defines graphics windows as a playground for the drawing turtles. Its constructor needs a tkinter.Canvas or a ScrolledCanvas as argument. It should be used when turtle is used as part of some application. The function Screen() returns a singleton object of a TurtleScreen subclass. This function should be used when turtle is used as a standalone tool for doing graphics. As a singleton object, inheriting from its class is not possible. All methods of TurtleScreen/Screen also exist as functions, i.e. as part of the procedure-oriented interface.
- RawTurtle (alias: RawPen ) defines Turtle objects which draw on a TurtleScreen . Its constructor needs a Canvas, ScrolledCanvas or TurtleScreen as argument, so the RawTurtle objects know where to draw. Derived from RawTurtle is the subclass Turtle (alias: Pen ), which draws on “the” Screen instance which is automatically created, if not already present. All methods of RawTurtle/Turtle also exist as functions, i.e. part of the procedure-oriented interface.
The procedural interface provides functions which are derived from the methods of the classes Screen and Turtle . They have the same names as the corresponding methods. A screen object is automatically created whenever a function derived from a Screen method is called. An (unnamed) turtle object is automatically created whenever any of the functions derived from a Turtle method is called.
To use multiple turtles on a screen one has to use the object-oriented interface.
In the following documentation the argument list for functions is given. Methods, of course, have the additional first argument self which is omitted here.
Drawing on the Screen
In this lesson, you’ll start drawing on the screen using a Surface . Recall that a Surface is a rectangular object on which you can draw, like a blank sheet of paper. The screen object is a Surface , and you can create your own Surface objects separate from the display screen.
You’ll fill the screen with white, and add a new Surface object to display on the screen. Add the code below your existing code, starting at line 44. Note the indentation, keeping the lines you are adding within the game loop, but outside the event loop:
44# Fill the screen with white 45screen.fill((255, 255, 255)) 46 47# Create a surface and pass in a tuple containing its length and width 48surf = pygame.Surface((50, 50)) 49 50# Give the surface a color to separate it from the background 51surf.fill((0, 0, 0)) 52rect = surf.get_rect()
For more information about the Surface and Rect classes, check out the following resources from the pygame documentation: