Pygame开发中如何跨函数传值实现按钮文字叠加且保障函数可复用
解决方案
我们仅需要对现有函数做两处极小的无侵入修改,即可在保留函数通用性的前提下实现需求:
1. 修改screen_text函数,返回生成的文本surface
原screen_text仅负责把文本绘制到屏幕,没有返回生成的文本对象,我们补充返回值即可,原有调用逻辑完全不受影响:
def screen_text(text,size,posx,posy): _text = pygame.font.Font('freesansbold.ttf',size) text_surf,text_rect = text_objects(text,_text) text_rect.center = ((posx),(posy)) screen.blit(text_surf,text_rect) return text_surf # 新增返回文本surface对象
2. 为screen_but新增可选文本参数,补充绘制逻辑
给screen_but加一个默认值为None的可选文本参数,同时修复原代码中mouse变量未定义就使用的bug:
# 新增可选参数text_surf,默认值None保证原有调用逻辑兼容 def screen_but(w1,w2,h1,h2, text_surf=None): while True: mouse = pygame.mouse.get_pos() # 移到事件循环前,避免未定义报错 for ev in pygame.event.get(): if ev.type == pygame.MOUSEBUTTONUP: if w1 <= mouse[0] <= w2 and h1 <= mouse[1] <= h2: return # 原有按钮绘制逻辑不变 if w1 <= mouse[0] <= w2 and h1 <= mouse[1] <= h2: pygame.draw.rect(screen,GREY,[w1,h1,(w2-w1),(h2-h1)]) else: pygame.draw.rect(screen,BLACK,[w1,h1,(w2-w1),(h2-h1)]) # 新增文本绘制逻辑,没有传文本时自动跳过 if text_surf is not None: # 此处如果需要文本在按钮内居中,可替换为居中计算逻辑 # text_x = w1 + (w2 - w1)/2 - text_surf.get_width()/2 # text_y = h1 + (h2 - h1)/2 - text_surf.get_height()/2 # screen.blit(text_surf, (text_x, text_y)) screen.blit(text_surf, (w1+10, h1+10)) pygame.display.update()
3. 业务调用调整
提前生成按钮需要的文本surface,传入按钮函数即可:
screen_text('Zombie Game',75,400,100) # 提前生成按钮文本surface play_text = screen_text('Play',35,400,300) # 传入按钮函数即可实现文本叠加 play_but = screen_but(365,440,280,320, text_surf=play_text)
该修改方式完全保留原有函数的通用性:不需要叠加文本的按钮场景,仍可以和之前一样直接调用screen_but(w1,w2,h1,h2),screen_text的原有调用逻辑也完全不受影响,新增的返回值不需要接收即可正常使用。
内容的提问来源于stack exchange,提问作者Tyler Westbury
相关产品推荐
相关产品推荐

