如何在tkinter设置页与pygame游戏文件间共享窗口尺寸变量?
解决Tkinter设置页与Pygame窗口共享尺寸变量的方案
你之前尝试用函数返回值传递变量无效,是因为导入时变量已完成初始化,返回值无法自动更新全局可访问的存储位置。以下是几种可行的实现方案:
方案1:用独立模块存储全局配置
创建一个专门的配置模块,用来共享全局变量,修改后其他文件能直接读取最新值。
- 创建
config.py模块:
# config.py window_width = 800 window_height = 600
- 在Tkinter设置页(如
settings.py)中修改配置:
import tkinter as tk import config def update_window_size(): selected_size = size_var.get() if selected_size == "small": config.window_width, config.window_height = 640, 480 elif selected_size == "medium": config.window_width, config.window_height = 800, 600 elif selected_size == "large": config.window_width, config.window_height = 1024, 768 root.geometry(f"{config.window_width}x{config.window_height}") root = tk.Tk() size_var = tk.StringVar(value="medium") # 单选按钮布局 tk.Radiobutton(root, text="小窗口(640x480)", variable=size_var, value="small", command=update_window_size).pack() tk.Radiobutton(root, text="中窗口(800x600)", variable=size_var, value="medium", command=update_window_size).pack() tk.Radiobutton(root, text="大窗口(1024x768)", variable=size_var, value="large", command=update_window_size).pack() # 启动游戏 def start_game(): root.destroy() import pygame_game pygame_game.run() tk.Button(root, text="开始游戏", command=start_game).pack() root.mainloop()
- 在Pygame游戏文件(如
pygame_game.py)中读取配置:
import pygame import config def run(): pygame.init() screen = pygame.display.set_mode((config.window_width, config.window_height)) pygame.display.set_caption("贪吃蛇") running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False screen.fill((0,0,0)) pygame.display.flip() pygame.quit()
方案2:用JSON文件持久化设置
如果需要让窗口尺寸设置在程序重启后依然生效,可以用配置文件存储。
- Tkinter设置页中写入配置:
import json def update_window_size(): selected_size = size_var.get() if selected_size == "small": width, height = 640, 480 elif selected_size == "medium": width, height = 800, 600 elif selected_size == "large": width, height = 1024, 768 root.geometry(f"{width}x{height}") # 写入配置文件 with open("game_config.json", "w") as f: json.dump({"width": width, "height": height}, f)
- Pygame文件中读取配置:
import pygame import json def run(): # 读取配置,不存在则用默认值 try: with open("game_config.json", "r") as f: config = json.load(f) width = config.get("width", 800) height = config.get("height", 600) except FileNotFoundError: width, height = 800, 600 pygame.init() screen = pygame.display.set_mode((width, height)) # 游戏逻辑...
方案3:直接传递参数给Pygame主函数
启动游戏时直接把尺寸作为参数传递,避免全局变量依赖。
- Tkinter设置页中传递参数:
def start_game(): root.destroy() import pygame_game pygame_game.run(config.window_width, config.window_height)
- Pygame文件中接收参数:
import pygame def run(width, height): pygame.init() screen = pygame.display.set_mode((width, height)) # 游戏逻辑...
内容的提问来源于stack exchange,提问作者Kai Tribble
相关产品推荐
相关产品推荐

