移动Pygame Surface时Thorpy按钮点击区域未同步移动问题
问题原因
你遇到的核心问题是:Thorpy的GUI元素是基于你绑定的surface来计算点击判定区域的,但你通过blit将该Surface偏移到屏幕的(100,0)位置时,Thorpy并不知道这个屏幕偏移量——它依然用屏幕原始坐标来判断点击,导致视觉位置和点击区域差了100像素。
解决方案
以下两种方法都能解决这个问题,推荐第一种更简洁的实现方式:
方案一:直接绑定Thorpy到屏幕,同步GUI与Surface偏移
放弃将Thorpy绑定到单独的Surface,直接绑定到主屏幕,然后让GUI组的位置和Surface的blit偏移保持一致,这样视觉和点击区域会同步移动:
import pygame import thorpy as tp pygame.init() def GUI_elements(): # 直接绑定Thorpy到主屏幕 tp.init(screen, tp.theme_round) button1 = tp.Button('Main Menu') button2 = tp.Button('Exit Game') group = tp.Group([button1, button2], 'v') # 设置GUI组的左上角位置,和Surface的blit偏移完全一致 group.set_topleft((100, 0)) game_GUI = group.get_updater() return game_GUI screen = pygame.display.set_mode((800, 600)) pygame.display.set_caption("Pygame Window") surface = pygame.Surface((400, 800)) def main_loop(): game_GUI = GUI_elements() menu_button = game_GUI.element.children[0] menu_button.at_unclick = exit exit_button = game_GUI.element.children[1] exit_button.at_unclick = exit running = True while running: game_GUI.update() for event in pygame.event.get(): if event.type == pygame.QUIT: running = False screen.fill((255, 0, 0)) # Surface依然blit到偏移位置,和GUI组位置同步 screen.blit(surface, (100, 0)) surface.fill((0, 0, 200)) pygame.display.flip() if __name__ == '__main__': main_loop() pygame.quit()
方案二:保留Surface绑定,手动转换事件坐标
如果必须将Thorpy绑定到单独的Surface,可以在事件传递给Thorpy前,把屏幕坐标转换为Surface的本地坐标(即减去偏移量):
import pygame import thorpy as tp pygame.init() def GUI_elements(): tp.init(surface, tp.theme_round) button1 = tp.Button('Main Menu') button2 = tp.Button('Exit Game') group = tp.Group([button1, button2], 'v') game_GUI = group.get_updater() return game_GUI screen = pygame.display.set_mode((800, 600)) pygame.display.set_caption("Pygame Window") surface = pygame.Surface((400, 800)) def main_loop(): game_GUI = GUI_elements() menu_button = game_GUI.element.children[0] menu_button.at_unclick = exit exit_button = game_GUI.element.children[1] exit_button.at_unclick = exit # 记录Surface的屏幕偏移量 surf_offset = (100, 0) running = True while running: # 预处理所有事件,转换鼠标坐标为Surface本地坐标 for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # 对带坐标的鼠标事件,减去偏移量 if hasattr(event, 'pos'): event.pos = (event.pos[0] - surf_offset[0], event.pos[1] - surf_offset[1]) # 将转换后的事件传递给Thorpy处理 game_GUI.react(event) screen.fill((255, 0, 0)) screen.blit(surface, surf_offset) surface.fill((0, 0, 200)) # 将GUI元素绘制到绑定的Surface上 game_GUI.draw() pygame.display.flip() if __name__ == '__main__': main_loop() pygame.quit()
内容的提问来源于stack exchange,提问作者webaccounts
相关产品推荐
相关产品推荐

