为何我的Pygame代码无法绘制所需的开始按钮?
解决Pygame按钮不显示的问题
你的代码核心问题是绘制顺序错误:你先调用start.draw()绘制按钮,之后又用screen.blit(bg,(0,0))绘制背景,背景会完全覆盖住按钮,导致按钮无法显示。
只需交换这两行代码的顺序,先绘制背景,再绘制按钮即可:
import pygame pygame.init() screen = pygame.display.set_mode((3840,2160)) running = True mouse = pygame.mouse.get_pos() pygame.display.set_caption("GermanBall") bg = pygame.image.load("Tan.jpg") icon = pygame.image.load("box.png") button1 = pygame.image.load("shirt.png").convert_alpha() class Button(): def __init__(self,x,y,image): self.image = image self.rect = self.image.get_rect() self.rect.topleft = (x,y) def draw(self): screen.blit(self.image,(self.rect.x,self.rect.y)) start = Button(0,0,button1) pygame.display.set_icon(icon) while running == True: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False screen.blit(bg,(0,0)) # 先绘制背景 start.draw() # 再绘制按钮 pygame.display.update()
另外可以额外检查以下几点,避免其他潜在问题:
- 确认
shirt.png图片文件路径正确,和代码文件在同一目录下,或者使用完整路径 - 如果按钮图片尺寸过小,在3840x2160的大窗口里可能不容易被注意到,可以调整按钮的位置或缩放图片
内容的提问来源于stack exchange,提问作者vivaan tomar
相关产品推荐
相关产品推荐

