Skip to content
Advertisement

Python3 PyGame how to move an image?

I tried to use .blit but an issue occurs, here is a screenshot to explain my problem furthermore:

The image appears to be smudged across the screen following my mouse

It just copies my image.

code:

import pygame   
import keyboard
black = (0,0,0)
white = (255, 255, 255)

pygame.init()

screen = pygame.display.set_mode((600, 400))
screen.fill(black)
screen.convert()

icon = pygame.image.load('cross.png')
pygame.display.set_icon(icon)
pygame.display.set_caption('MouseLoc')
cross = pygame.image.load('cross.png')


running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT or keyboard.is_pressed(' '):
            running = False
            
mx, my = pygame.mouse.get_pos()
screen.blit(cross, (mx-48, my-48))
print(my, mx)
pygame.display.update() 

Advertisement

Answer

Fix the indentation in your given code, it puts all the important stuff outside the while loop. You can also add a function that redraws the window each time the sprite is moved:

def redraw_game_window():
    screen.fill(black)
    screen.blit(•••)
    pygame.display.update()

And put this at the end of your program, after putting all fill and blit statements inside the function:

redraw_game_window()

This function will make it easier for you to blit more items on the screen, and this will prevent the object from drawing on the screen, because the screen is updated every time the object is moved.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement