【问题标题】:Python Global-variables don't change in my functionPython 全局变量在我的函数中没有改变
【发布时间】:2017-03-15 18:14:52
【问题描述】:

我想在其他文件中使用全局变量并更改此变量的值: 设置.py:

mort = False

平台1.py:

class Platform(pygame.sprite.Sprite):
    #..........
class Spike(Platform):
player = None
def invisible(self):
    if not pygame.sprite.collide_rect(self, self.player):
        self.image.set_alpha(0)
def update(self):
    global mort
    if pygame.sprite.collide_rect(self, self.player):
        self.image.set_alpha(256)
        mort = True
        print(mort)
>>>True

我可以像这样在我的关卡中添加尖峰: 级别1.py:

import pygame
from settings import *
from platforms1 import *

#add a spike (image, width, height)
block = Spike(spikes,1,1)
block.rect.x = 1360 #pos en x
block.rect.y = 696 #pos en y
block.player = self.player
Spike.invisible(block)
self.background_list.add(block)

并添加到我的主循环中: 主.py:

while mort == True:
    #.................
active_sprite_list.update()
current_level.update()
print(mort)
>>>False

您可以在 main.py 中看到“mort”保持为假,并且在 mort == True 时明显不执行:在platforms1.py 中“mort”为真时循环。

如果您需要更多代码,我想我在这里找到了最重要的代码,但如果您愿意,我可以粘贴更多。

感谢您的建议,抱歉我的英语不好,我是法国人!

【问题讨论】:

    标签: function python-3.x class pygame global-variables


    【解决方案1】:

    当你这样做时

    from platforms1 import *
    

    您将platforms1 中的对象绑定到当前模块中的新变量。现在您有 2 个对这些对象的引用。当platforms1 中的代码重新绑定其本地引用(例如mort = True)时,其他模块中的引用不受影响。如果你想在多个模块中使用同一个对象,不要这样做import *。而是

    import platforms1
    while platforms1.mort:
        ...
    

    【讨论】:

      猜你喜欢
      • 2019-09-15
      • 1970-01-01
      • 2021-05-31
      • 1970-01-01
      • 1970-01-01
      • 2012-05-22
      相关资源
      最近更新 更多