首页 > 解决方案 > 为什么离开函数后变量不更新?

问题描述

我制作了一个滑块,它应该更新我制作的网格的大小。单击并移动滑块时,滑块的值会发生变化,但网格大小保持不变并且不会更新。我将如何解决这个问题?谢谢。

这是我用来更新滑块值的函数。在游戏循环中单击滑块时调用

def slider_loop(s):
    s.move()
    grid_size = int(slider_value.val)
    return grid_size

这是主游戏循环中调用滑块循环的部分

    for s in slides:
        if s.hit:
            slider_loop(s)

这是滑块类

class slider():
    def __init__(self, name, val, maxi, mini, x_pos, y_pos):
        font = pygame.font.SysFont("Verdana", 12)
        self.val = val  # start value
        self.maxi = maxi  # maximum at slider position right
        self.mini = mini  # minimum at slider position left
        self.xpos = x_pos  # x-location on screen
        self.ypos = y_pos
        self.surf = pygame.surface.Surface((100, 50))
        self.hit = False  # the hit attribute indicates slider movement due to mouse interaction

        self.txt_surf = font.render(name, 1, black)
        self.txt_rect = self.txt_surf.get_rect(center=(50, 15))

        # Static graphics - slider background #
        self.surf.fill((100, 100, 100))
        pygame.draw.rect(self.surf, grey, [0, 0, 100, 50], 3)
        pygame.draw.rect(self.surf, orange, [10, 10, 80, 10], 0)
        pygame.draw.rect(self.surf, white, [10, 30, 80, 5], 0)

        self.surf.blit(self.txt_surf, self.txt_rect)  # this surface never changes

        # dynamic graphics - button surface #
        self.button_surf = pygame.surface.Surface((20, 20))
        self.button_surf.fill(trans)
        self.button_surf.set_colorkey(trans)
        pygame.draw.circle(self.button_surf, black, (10, 10), 6, 0)
        pygame.draw.circle(self.button_surf, orange, (10, 10), 4, 0)

    def draw(self):
        """ Combination of static and dynamic graphics in a copy of
the basic slide surface
"""
        # static
        surf = self.surf.copy()

        # dynamic
        pos = (10+int((self.val-self.mini)/(self.maxi-self.mini)*80), 33)
        self.button_rect = self.button_surf.get_rect(center=pos)
        surf.blit(self.button_surf, self.button_rect)
        self.button_rect.move_ip(self.xpos, self.ypos)  # move of button box to correct screen position

        # screen
        screen.blit(surf, (self.xpos, self.ypos))

    def move(self):
        """
The dynamic part; reacts to movement of the slider button.
"""
        self.val = (pygame.mouse.get_pos()[0] - self.xpos - 10) / 80 * (self.maxi - self.mini) + self.mini
        if self.val < self.mini:
            self.val = self.mini
        if self.val > self.maxi:
            self.val = self.maxi

标签: pythonpygame

解决方案


看起来 grid_size 由 slider_loop 返回,但从未在您的代码中使用。做类似的事情

new_grid_size = slider_loop(s) 

如果你想得到它。


推荐阅读