英文:
How to scale multiple images with a for loop?
问题
我正在尝试使用for循环来遍历一组self类。我希望给它们都应用相同的缩放。
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("Migue/m_normal.png")
self.quieto = pygame.image.load("Migue/m_normal.png")
self.andando = pygame.image.load("Migue/m_andando_normal.png")
self.image = pygame.transform.scale(self.image, sizenorm)
states = [self.quieto, self.andando]
for i in states:
i = pygame.transform.scale(i, sizenorm)
英文:
I'm trying to use a for-loop to iterate through a list of self classes. I want to give each one the same scale.
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("Migue/m_normal.png")
self.quieto = pygame.image.load("Migue/m_normal.png")
self.andando = pygame.image.load("Migue/m_andando_normal.png")
self.image = pygame.transform.scale(self.image, sizenorm)
states = [self.quieto, self.andando]
for i in states:
i = pygame.transform.scale(i, sizenorm)
This wont work, but I can achieve the result using this:
self.quieto = pygame.transform.scale(self.quieto, sizenorm)
self.andando = pygame.transform.scale(self.andando, sizenorm)
The problem is that I have to make a lot of more states, and using that for loop would be shorter. However, it doesn't work like the lower example does. I don't know what's wrong with the loop.
答案1
得分: 1
状态列表 = [self.quieto, self.andando]
状态列表 = [pygame.transform.scale(i, sizenorm) for i in 状态列表]
(self.quieto, self.andando) = 状态列表
(self.quieto, self.andando) = [pygame.transform.scale(i, sizenorm) for i in [self.quieto, self.andando]]
文件名列表 = ["Migue/m_normal.png", "Migue/m_andando_normal.png"]
self.states = [pygame.transform.scale(pygame.image.load(n), sizenorm) for n in 文件名列表]
英文:
You can create a list of the scaled objects and assign the elements of the list to the original attributes:
states = [self.quieto, self.andando]
states = [pygame.transform.scale(i, sizenorm) for i in states]
(self.quieto, self.andando) = states
This can even be written in a single line
(self.quieto, self.andando) = [pygame.transform.scale(i, sizenorm) for i in [self.quieto, self.andando]]
Alternatively, you can simply put the images in a list:
filenames = ["Migue/m_normal.png", "Migue/m_andando_normal.png"]
self.states = [pygame.transform.scale(pygame.image.load(n), sizenorm) for n in filenames]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论