如何在Pygame的backscreen.surface上添加并显示选择按钮?
解决Pygame中按钮显示在背景之上的问题
Pygame的渲染逻辑是按代码执行顺序分层:先绘制的元素会被后绘制的元素覆盖。你之前的问题大概率是把按钮绘制在了背景之前,或者按钮代码本身有错误导致背景被覆盖。
下面是完整的可运行代码,包含两个选择按钮,且按钮会正确显示在背景图上方:
import pygame import sys pygame.init() screen = pygame.display.set_mode((520, 680)) clock = pygame.time.Clock() pygame.display.set_caption("everlasting night") main_font = pygame.font.Font("/Users//Desktop/dpcomic.ttf", 65) button_font = pygame.font.Font("/Users//Desktop/dpcomic.ttf", 40) # 加载背景图 backscreen_surface = pygame.image.load("//Users//Desktop/snow.jpeg") # 缩放背景图适配窗口(可选,如果图片尺寸和窗口不一致) backscreen_surface = pygame.transform.scale(backscreen_surface, (520, 680)) text_surface = main_font.render("go home?", False, "Black") # 定义按钮属性:矩形区域、文字、颜色 button_yes = pygame.Rect(100, 200, 150, 80) button_no = pygame.Rect(270, 200, 150, 80) button_yes_text = button_font.render("YES", False, "White") button_no_text = button_font.render("NO", False, "White") while True: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # 检测按钮点击 if event.type == pygame.MOUSEBUTTONDOWN: if button_yes.collidepoint(event.pos): print("Clicked YES") if button_no.collidepoint(event.pos): print("Clicked NO") # 1. 先绘制背景(最底层) screen.blit(backscreen_surface, (0, 0)) # 2. 绘制标题文字 screen.blit(text_surface, (140, 560)) # 3. 绘制按钮(背景之上) pygame.draw.rect(screen, (0, 100, 200), button_yes) pygame.draw.rect(screen, (150, 0, 0), button_no) # 4. 绘制按钮文字 screen.blit(button_yes_text, (button_yes.x + 35, button_yes.y + 15)) screen.blit(button_no_text, (button_no.x + 35, button_no.y + 15)) pygame.display.update()
关键注意点:
- 必须保证背景图的绘制代码
screen.blit(backscreen_surface, (0, 0))在所有按钮绘制代码之前 - 如果背景图尺寸和窗口不一致,用
pygame.transform.scale缩放适配,避免背景显示不全 - 按钮的绘制分为两步:先画矩形底色,再画按钮文字,确保文字在按钮矩形之上
内容的提问来源于stack exchange,提问作者sfrjke
相关产品推荐
相关产品推荐

