如何使用for循环批量缩放多个图像?

huangapple go评论94阅读模式
英文:

How to scale multiple images with a for loop?

问题

  1. 我正在尝试使用for循环来遍历一组self我希望给它们都应用相同的缩放
  2. def __init__(self):
  3. pygame.sprite.Sprite.__init__(self)
  4. self.image = pygame.image.load("Migue/m_normal.png")
  5. self.quieto = pygame.image.load("Migue/m_normal.png")
  6. self.andando = pygame.image.load("Migue/m_andando_normal.png")
  7. self.image = pygame.transform.scale(self.image, sizenorm)
  8. states = [self.quieto, self.andando]
  9. for i in states:
  10. 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.

  1. def __init__(self):
  2. pygame.sprite.Sprite.__init__(self)
  3. self.image = pygame.image.load("Migue/m_normal.png")
  4. self.quieto = pygame.image.load("Migue/m_normal.png")
  5. self.andando = pygame.image.load("Migue/m_andando_normal.png")
  6. self.image = pygame.transform.scale(self.image, sizenorm)
  7. states = [self.quieto, self.andando]
  8. for i in states:
  9. i = pygame.transform.scale(i, sizenorm)

This wont work, but I can achieve the result using this:

  1. self.quieto = pygame.transform.scale(self.quieto, sizenorm)
  2. 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

  1. 状态列表 = [self.quieto, self.andando]
  2. 状态列表 = [pygame.transform.scale(i, sizenorm) for i in 状态列表]
  3. (self.quieto, self.andando) = 状态列表
  1. (self.quieto, self.andando) = [pygame.transform.scale(i, sizenorm) for i in [self.quieto, self.andando]]
  1. 文件名列表 = ["Migue/m_normal.png", "Migue/m_andando_normal.png"]
  2. 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:

  1. states = [self.quieto, self.andando]
  2. states = [pygame.transform.scale(i, sizenorm) for i in states]
  3. (self.quieto, self.andando) = states

This can even be written in a single line

  1. (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:

  1. filenames = ["Migue/m_normal.png", "Migue/m_andando_normal.png"]
  2. self.states = [pygame.transform.scale(pygame.image.load(n), sizenorm) for n in filenames]

huangapple
  • 本文由 发表于 2023年2月19日 03:18:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75495796.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定