我制作了 2 個按鈕,并讓它們在單擊它們時發送訊息“開始”或“退出”,但我可以單擊它們的范圍大于實際按鈕,因此我可以單擊按鈕周圍并且它仍然有效。當在它們附近單擊時,它還會發送這兩條訊息。我試過改變圖片,但它仍然做同樣的事情。我不知道我該怎么辦?我是新手,請幫忙。
這是我的主要內容:
import pygame
import button
window_width, window_height = 1000, 650
win = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("My game!")
grey = (25, 25, 25)
FPS = 60
start_img = pygame.image.load("img/start_button.png")
exit_img = pygame.image.load("img/exit_button.png")
start_button = button.Button(250, 220, start_img, 1.2)
exit_button = button.Button(265, 350, exit_img, 1.2)
def draw_window():
win.fill(grey)
def main():
clock = pygame.time.Clock()
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
draw_window()
if start_button.draw_button(win):
print("START")
if exit_button.draw_button(win):
print("EXIT")
pygame.display.flip()
pygame.quit()
if __name__ == "__main__":
main()
這是我的按鈕:
import pygame
class Button:
def __init__(self, x, y, image, scale):
width = image.get_width()
height = image.get_height()
self.image = pygame.transform.scale(image, ((width * scale), (height * scale)))
self.rect = self.image.get_rect()
self.rect.topleft = (x, y)
self.clicked = False
def draw_button(self, surface):
action = False
pos = pygame.mouse.get_pos()
if self.rect.collidepoint(pos):
if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False:
self.clicked = True
action = True
if pygame.mouse.get_pressed()[0] == 0:
self.clicked = False
surface.blit(self.image, (self.rect.x, self.rect.y))
return action
我不知道它可能是什么,請提供任何建議,不勝感激。
uj5u.com熱心網友回復:
你的代碼沒有問題,我測驗過了。問題在于按鈕影像。可能您的影像有一個大的透明區域。您可以通過使用創建一個較小的命中矩形來彌補這一點get_bounding_rect()。
另請參閱如何獲取從影像創建的 pygame 矩形的正確尺寸
import pygame
class Button:
def __init__(self, x, y, image, scale):
width = image.get_width()
height = image.get_height()
self.image = pygame.transform.scale(image, ((width * scale), (height * scale)))
self.rect = self.image.get_rect()
self.rect.topleft = (x, y)
self.clicked = False
self.hit_rect = self.image.get_bounding_rect()
self.hit_rect.x = x
self.hit_rect.y = y
def draw_button(self, surface):
action = False
pos = pygame.mouse.get_pos()
if self.hit_rect.collidepoint(pos):
if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False:
self.clicked = True
action = True
if pygame.mouse.get_pressed()[0] == 0:
self.clicked = False
surface.blit(self.image, (self.rect.x, self.rect.y))
return action
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/447673.html
上一篇:按鈕btn1_click未執行
下一篇:CSS如何防止鍵盤向上移動內容?
