如何使用 pygame 从 python 中的用户指定文件夹导入所有图像
要从用户指定的文件夹中导入所有图像并在 Pygame 中加载,可以按以下步骤操作:
tkinter.filedialog
os
.png
.jpg
pygame.image.load
以下是完整的代码实现:
import os import pygame from tkinter import Tk from tkinter.filedialog import askdirectory def load_images_from_folder(folder): """加载指定文件夹中的所有图像""" images = {} supported_formats = ('.png', '.jpg', '.jpeg', '.bmp', '.gif') for filename in os.listdir(folder): if filename.lower().endswith(supported_formats): filepath = os.path.join(folder, filename) try: images[filename] = pygame.image.load(filepath).convert_alpha() except pygame.error as e: print(f"无法加载图像 {filename}: {e}") return images def main(): # 初始化 Pygame pygame.init() # 创建窗口 screen = pygame.display.set_mode((800, 600)) pygame.display.set_caption("图像加载器") # 选择文件夹 Tk().withdraw() # 隐藏 Tkinter 主窗口 folder = askdirectory(title="选择包含图像的文件夹") if not folder: print("未选择文件夹。") return # 加载图像 images = load_images_from_folder(folder) print(f"加载了 {len(images)} 张图像:{list(images.keys())}") # 显示图像 running = True image_keys = list(images.keys()) current_image_index = 0 while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: # 切换到下一张图像 current_image_index = (current_image_index + 1) % len(image_keys) elif event.key == pygame.K_LEFT: # 切换到上一张图像 current_image_index = (current_image_index - 1) % len(image_keys) # 清屏 screen.fill((0, 0, 0)) # 显示当前图像 if images: current_image = images[image_keys[current_image_index]] rect = current_image.get_rect(center=screen.get_rect().center) screen.blit(current_image, rect.topleft) # 刷新屏幕 pygame.display.flip() pygame.quit() if __name__ == "__main__": main()
supported_formats
tkinter.filedialog.askdirectory
pygame
tkinter
pip install pygame