【问题标题】:Select a random image from a file and display it using pygame从文件中选择一个随机图像并使用 pygame 显示它
【发布时间】:2020-05-26 17:57:33
【问题描述】:

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

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。

【问题讨论】:

  • 注意,当您执行question = choice(path.join(examQ_dir)) 时,choice 的参数是一个字符串(文件路径)。您实际上从文件路径中选择了一个随机字母。什么是图像文件?你是说精灵表吗?见Spritesheet
  • 如果您想从目录中的可用文件中随机选择一个文件,您应该首先生成一个可能文件列表,然后随机选择其中一个。请参阅:stackoverflow.com/questions/3207219/… 以获得良好的开始
  • @Hoog 问题不在于目录中的多个文件(请参阅已删除的答案)。问题是关于一个位图文件(精灵表)中的多个图像(精灵)。
  • @Hoog 非常感谢你,这正是我想要的。
  • @Rabbid76 不,我没有使用 spritesheet,但这个解释帮助我弄清楚我在使用选择功能时做错了什么,所以谢谢。

标签: python image pygame pycharm


【解决方案1】:

您必须使用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)

注意,当您执行question = choice(path.join(examQ_dir)) 时,choice 的参数是一个字符串(文件路径)。您实际上从文件路径中选择了一个随机字母。

【讨论】:

    猜你喜欢
    • 2016-03-18
    • 2012-06-10
    • 1970-01-01
    • 2013-06-13
    • 2019-05-12
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    • 2020-07-03
    相关资源
    最近更新 更多