【问题标题】:How to fix 'NoneType' object is not subscriptable' error in while loop如何修复 while 循环中的“NoneType”对象不可下标“错误
【发布时间】:2019-04-05 20:43:46
【问题描述】:

Windows 10 蟒蛇 3.7 蟒蛇 1.9.7 蜘蛛3.3.3 Python 2.7 的 PsychoPy

我正在编写一个实验,该实验需要以随机顺序呈现图像以供参与者响应。我能够以数组的形式获取图像,但是为了一次呈现一个图像,我使用了一个带有一个变量的 while 循环,该变量每次通过循环时都会增加 1。它没有将变量识别为数字,因此数组不能调用任何东西。

我尝试不对变量进行随机化以查看这是否是问题所在,但似乎我的变量 i 没有被读取为数字

#import packages
import random, os
from psychopy import core, visual, event
from PIL import Image

#setup screen with specs and draw
win = visual.Window([400, 300], monitor="testMonitor")
message = visual.TextStim(win, text="")

message.draw()
win.flip()
core.wait(3.0)

#set image size and populate array with images
stim_size = (0.8, 0.8)
image = [i for i in os.listdir('C:/Users/*/psychopy-tests') 
                    if i.endswith('.bmp')]
#randomize image order
images = random.shuffle(image)

这似乎是我的问题所在

i = 0
while i != 29: #there are only 28 images
    
    new = images[i] #this is where the issue is
    image_stim = Image.open(new)

    stim = visual.ImageStim(win, image_stim, size = (stim_size))
    stim.draw()
    win.update()
    output = []
    if event.getKeys(keyList=['space']):
        output[i] = 1
    if event.getKeys(['escape']):
        win.close()
        core.quit()
    if event.getKeys(keyList=None):
        output[i] = 0
        core.wait(5.0)
    i = i + 1

【问题讨论】:

  • 其他一些注意事项:而不是这个whilefor new in image:。然后在循环上方定义stim,并在循环中执行stim.image = new。这将更快更安全。不再需要变量i
  • 我无法向您显示输出,但是从循环中删除 stim = visual.ImageStim(win, image, size = (stim_size)) 可以防止单独打开图像。我收到错误“无法理解请求的图像”
  • images = random.shuffle(image) - shuffle 就地随机播放并返回 None。除非您稍后将images 设置为其他东西,否则其中不可能有任何东西。见docs.python.org/3.7/library/random.html#random.shuffle
  • 如果您只有 28 张图片,请从 i = 1 开始并递增直到 while i != 29: 您尝试制作 29 张图片:0,1,2,3,4,5,6,7, 8,9 等:0-9 == 10 张图片,0-19== 20 张图片,0-28 == 29 张图片

标签: python-2.7 while-loop anaconda psychopy


【解决方案1】:

random.shuffle 随机播放,不返回任何内容,即返回 None。

因此images 为 None 且不可下标。

source

【讨论】:

  • 当我打印出洗牌后的数组时,尽管它显示它已经正确工作
  • 还有其他功能可以使用吗?
  • 您打印了images 并且有效?不是image 而是images
  • 我单独打印图像是的,它以随机顺序返回我的图像列表。正如我所说,删除随机化并没有解决这个问题“NoneType”
  • 我刚刚测试过。如前所述,images 将是无。我不明白您是如何设法打印 None 对象的。你是说你用了print(images)(复数)
猜你喜欢
  • 1970-01-01
  • 2019-09-27
  • 2020-02-22
  • 2019-10-04
  • 1970-01-01
  • 1970-01-01
  • 2013-01-13
  • 2017-03-11
  • 1970-01-01
相关资源
最近更新 更多