Search code examples
pythongraphicspygamepython-idle

PyGame - Plotting a Pixel and Printing out it's coordinates


This may seem like a really easy question to answer, but I'm just a beginner in need of quick help.

I'm trying to create a program that when you click somewhere on the pyGame window, it'll print out that you hit it with the left button on the mouse, and also print out co-ordinates of where it was pressed. I've got this already. I'm having problems with making it plot the pixel on the pyGame window. Basically, I want it to draw a pixel where I pressed down on the pyGame window.

#!/usr/bin/env python

#import the module for use 
import pygame

#setting up some variables
running = 1
LEFT = 1 
#Set up the graphics area/screen
screen=pygame.display.set_mode((640,400))

#continuous loop to keep the graphics running
while running==1:
    event=pygame.event.poll()
    if event.type==pygame.QUIT:
        running=0
        pygame.quit()
    elif event.type==pygame.MOUSEBUTTONDOWN and event.button==LEFT:
        print "You pressed the left mouse button at (%d,%d)" %event.pos
    elif event.type==pygame.MOUSEBUTTONUP and event.button==LEFT:
        print "You released the left mouse button at (%d,%d)" %event.pos

Solution

  • Try setting the color of each pixel when you receive the mouse down event.

    elif event.type==pygame.MOUSEBUTTONDOWN and event.button==LEFT:
      print "You pressed the left mouse button at (%d,%d)" %event.pos
      screen.set_at((event.pos.x, event.pos.y), pygame.Color(255,0,0,255))
    

    Note that this will temporarily lock and unlock the Surface as needed.