2014-01-12 50 views
0

我有一个关于pyglet图像资源定义的问题。pyglet图像资源来自字典

如果我有很多图片,我可以在字典中描述它们并用for循环制作图片吗?

快捷的方式:

images = {'pic1':'pic1.jpg', 
      'pic2':'pic2.jpg', 
      ...} 

for (name, val) in images.items(): 
    # this is correct code 
    name = pyglet.resource.image(val) 

正常方式:

image1 = pyglet.resource.image("image1.jpg") 
image2 = pyglet.resource.image("image2.jpg") 
... 

与其他词我想用 '名' 为变量的名称,并宣布像playget.resource.image这个变量(VAL ),其中val是图像的名称。

+2

你有没有尝试它? – jonrsharpe

+0

是的,得到:AttributeError:'模块'对象没有属性'img1' – user3186945

+1

不是从你在这里的代码。请用完整的错误追溯和相关代码编辑您的问题。 – jonrsharpe

回答

2

下面会更有效地利用Dictionary Comprehension和发电机方法iteritems(如果使用的python 2.X):

{key: pyglet.resource.image(value) for k,v in images.iteritems()} 

,或者如果你有一个命名模式('pic1' =>“pic1.jpg”等):

{'pic%s' % index: pyglet.resource.image('pic%s.jpg' % index) for index in xrange(1, 1000)} 
+0

我编辑我的问题。当我使用第一行代码时,出现错误:“super(Player,self).__ init __(img = resources.img1,* args,** kwargs) AttributeError:'module'object has no attribute'img1'” – user3186945

+0

你可以发布你的代码(或其中的一部分)的播放器和资源? – astreal

0

我想找到解决办法,可能不是最好的,蟒蛇不是我的身边,如果有人有更好的办法让分享吧!
所以这个工作对我来说:在images.iteritems

的(键,值)():
     瓦尔()[关键] = pyglet.resource.image(值)