'I want to know how to change an image in PyGame with a single mouse click
import pygame
import cv2
from tkinter import *
root = Tk()
pygame.init()
img = cv2.imread('DATTGOH 1.png', 1)
img_half = cv2.resize(img, (0, 0), fx=0.25, fy=0.25)
cv2.imshow('Thing 1', img_half)
events = pygame.event.get()
for event in events:
if event.type == pygame.MOUSEBUTTONDOWN:
img = cv2.imread('DATTGOH 2.png', 1)
img_half = cv2.resize(img, (0, 0), fx=0.25, fy=0.25)
cv2.imshow('Thing 1', img_half)
pygame.display.update()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
That is my code so far. I've tried looking at other problems and solutions here, but I'm unsure. This is my first time using PyGame, relatively.
This is the first image labeled "DATTGOH 1".
This is the second image labeled "DATTGOH 2".
I want to know how to change an image in PyGame with a single mouse click.
What I want is for when the screen I clicked, the screen changes from the first image to the second.
Solution 1:[1]
pygame.init()
width=350;
height=400
screen = pygame.display.set_mode( (width, height ) )
pygame.display.set_caption('clicked on image')
redSquare = pygame.image.load("images/red-square.png").convert()
x = 20; # x coordnate of image
y = 30; # y coordinate of image
screen.blit(redSquare , ( x,y)) # paint to screen
pygame.display.flip() # paint screen one time
running = True
while (running):
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
# Set the x, y postions of the mouse click
x, y = event.pos
if redSquare.get_rect().collidepoint(x, y):
BlueSquare = pygame.image.load("images/Blue-square.png").convert()
screen.blit(BlueSquare , ( x,y))
#loop over, quite pygame
pygame.quit()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ansh |
