我试图用pygame制作一种虚拟电话程序,只是为了进行试验,但是遇到了一个问题。我已经加载了图像,然后将其在屏幕的左下方涂上了斑点。但是,当我执行print(imagename.get_rect())
时,它会在屏幕的0,0处打印出一个位置。
鼠标也在那里碰撞。我不明白什么?
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")
点击图像“ hi”时,预期结果将被打印。 实际结果是,当单击左上角hi时将被打印。
答案 0 :(得分:0)
get_rect
返回一个pygame.Rect,其默认的左上坐标为(0,0)。您需要随后设置坐标或将其作为关键字参数传递给get_rect
。
我建议将rect分配给另一个变量,并以下列方式之一设置坐标:
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))
还有更多rect attributes可以分配坐标:
x,y
top, left, bottom, right
topleft, bottomleft, topright, bottomright
midtop, midleft, midbottom, midright
center, centerx, centery