从文件中选择一个随机图像并使用pygame显示它

问题描述 投票:1回答:1

我有一个图像文件,并且我希望该文件夹选择一个随机文件并显示该图像。这是我到目前为止的代码:

dir = path.dirname(__file__)
examQ_dir = path.join(dir, 'Exam Questions')
question = choice(path.join(examQ_dir))

image_surface = pg.display.set_mode((850, 500))
image = pg.image.load(question)

我得到的错误如下:

Traceback (most recent call last):
  File "D:/A level Comp Sci/Platformer Game in Development Stages/Question.py", line 13, in <module>
    image = pg.image.load(question)
pygame.error: Couldn't open E

而且我每次运行它时,错误的最后一个字母有时都会说出一点不同

pygame.error: Couldn't open i

而其他时候根本没有任何东西。我认为我进行设置的逻辑有问题,但我无法解决。我正在使用PyCharm IDE。

python image pygame pycharm
1个回答
0
投票

您必须使用os.listdir来获取目录中的条目。使用os.listdir评估条目是否是文件:

os.isfile

注意,当您执行import os import random dir = os.path.dirname(__file__) examQ_dir = os.path.join(dir, 'Exam Questions') allpaths = [os.path.join(examQ_dir, entry) for entry in os.listdir(examQ_dir)] filepaths = [p for p in allpaths if os.isfile(p)] question = random.choice(filepaths) 时,choice的参数是字符串(文件路径)。您实际上是从文件路径中选择一个随机字母。

© www.soinside.com 2019 - 2024. All rights reserved.