0

I am trying to make a virtual phone kind of program with pygame, just to experiment with it, but i ran into a problem. I have loaded an image and then blitted it to the bottom left of the screen. But when i do print(imagename.get_rect()) it prints out a location at 0, 0 of the screen. also the mouse collides with it there. what am i not understanding?

def aloitus(): #goes back to the home screen
    cls() #clears the screen
    tausta = pygame.image.load("./pyhelin.png") #load background
    tausta = pygame.transform.scale(tausta, (360, 640)) #scale it 
    screen.blit(tausta, (0, 0)) #blit it
    alapalkki = pygame.Surface((600, 100)) #ignore
    alapalkki.set_alpha(120)
    alapalkki.fill(blonk)
    screen.blit(alapalkki, (0, 560))
    global messenger #this is the thing!
    messenger = pygame.image.load("./mese.png").convert_alpha() #load image
    print(messenger.get_rect()) #print its location
    messenger = pygame.transform.scale(messenger, (60,65)) #scale it to the correct size
    screen.blit(messenger, (10, 570)) # blit on the screen
    update() #update screen
aloitus() # at the start of the program, go to the home screen
while loop: #main loop
    for event in pygame.event.get():
         if event.type == pygame.MOUSEBUTTONDOWN:
            # Set the x, y postions of the mouse click
            x, y = event.pos
            if messenger.get_rect().collidepoint(x, y): #messenger is the image defined earlier
                #do things
                print("hi")

Expected result would be, when clicking on the image "hi" would be printed. actual result is that when topleft corner is clicked hi is printed.

Skelly
  • 109
  • 1
  • 10

1 Answers1

0

get_rect returns a pygame.Rect with the default top left coordinates (0, 0). You need to set the coordinates afterwards or pass them as a keyword argument to get_rect.

I suggest assigning the rect to another variable and set the coords in one of these ways:

messenger_rect = messenger.get_rect()
messenger_rect.x = 100
messenger_rect.y = 200
# or
messenger_rect.topleft = (100, 200)
# or pass the coords as an argument to `get_rect`
messenger_rect = messenger.get_rect(topleft=(100, 200))

There are even more rect attributes to which you can assign the coordinates:

x,y
top, left, bottom, right
topleft, bottomleft, topright, bottomright
midtop, midleft, midbottom, midright
center, centerx, centery
skrx
  • 19,980
  • 5
  • 34
  • 48