Python pygame导入settings.py后自动运行 点击账户按钮触发逻辑失效
问题原因
Python导入模块时会执行目标模块所有顶层代码,你的settings.py末尾直接写了无保护的mainloop()调用,同时顶层代码直接执行了pygame.display.set_mode修改窗口参数,所以只要执行import settings就会立刻触发设置页面运行,不会等按钮点击。
修复步骤
1. 修改settings.py
首先把顶层的窗口初始化代码移入mainloop函数,同时给末尾的mainloop()调用加运行判断,只有直接运行settings.py文件时才自动执行,还可以补充设置页退出逻辑,关闭后自动回到主菜单:
import pygame, sys, os import myLibrary as lib script_dir = sys.path[0] # 资源加载可以保留在顶层,不需要每次打开都重复加载 bg_path = os.path.join(script_dir, '../info/images/backgrounds/Settings background.png') bg = pygame.image.load(bg_path) Username_img = pygame.image.load(os.path.join(script_dir, '../info/images/Settings buttons/username.png')) def mainloop(): # 把窗口初始化移到函数内部,只有调用mainloop时才修改窗口 (width, height) = (1100, 700) screen = pygame.display.set_mode((width, height)) pygame.display.set_caption('Settings') while True: screen.blit(bg, (0,0)) screen.blit(Username_img, (30,20)) for event in pygame.event.get(): # 加退出逻辑,点击窗口叉号就关闭设置页回到主菜单 if event.type == pygame.QUIT: # 恢复主菜单窗口参数 main_width, main_height = 1300, 790 pygame.display.set_mode((main_width, main_height)) pygame.display.set_caption('Main Menu') return pygame.display.update() # 只有直接运行settings.py时才自动执行mainloop,导入时不会执行 if __name__ == '__main__': mainloop()
2. 调整main.py(可选优化)
可以把import settings移到runSettings函数内部,按需导入,避免程序启动时就加载settings的资源,同时删掉没用的print语句:
import pygame, sys, os import myLibrary as lib # 删掉顶部的import settings def runSettings(): import settings settings.mainloop() return script_dir = sys.path[0] bg_path = os.path.join(script_dir, '../info/images/backgrounds/MainMenu background.png') bg = pygame.image.load(bg_path) (width, height) = (1300, 790) screen = pygame.display.set_mode((width, height)) pygame.display.set_caption('Main Menu') Account_img = os.path.join(script_dir, '../info/images/MainMenu buttons/account.png') Account_btn = lib.Button(Account_img, (180,340), runSettings) while True: screen.blit(bg, (0, 0)) screen.blit(Account_btn.image, Account_btn.rect) for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: Account_btn.on_click(event) pygame.display.update()
修改后运行main.py就不会自动弹出设置页,只有点击Account按钮才会触发设置页面加载,关闭设置页后会自动回到主菜单。
内容的提问来源于stack exchange,提问作者twisting234
相关产品推荐
相关产品推荐

