Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在pygame中未按下按钮时,如何将按钮的值设置回False_Python_Pygame - Fatal编程技术网

Python 在pygame中未按下按钮时,如何将按钮的值设置回False

Python 在pygame中未按下按钮时,如何将按钮的值设置回False,python,pygame,Python,Pygame,你只需要在你的公司做一个else声明 class Button(): def __init__(self, x , y, height, width, color): self.X = x self.Y = y self. Height = height self.Width = width self.Color = color self.Pressed = False def dra

你只需要在你的公司做一个else声明

class Button():
    def __init__(self, x , y, height, width, color):
        self.X = x
        self.Y = y
        self. Height = height
        self.Width = width
        self.Color = color
        self.Pressed = False
    def draw(self, surface):
        pygame.draw.rect(surface, self.Color, (self.X, self.Y, self.Width, self.Height))
    def draw_text(self, text, surface):
        Text = font.render(text,1, black)
        surface.blit(Text, (self.X + self.Width//4, self.Y + self.Height//4 ))
    def mouse_event(self, surface, color):
        mouse = pygame.mouse.get_pos()
        click = pygame.mouse.get_pressed()

        #mous[0] is the x coordinate of the mouse and mouse[1] is the y coordinate
        if self.X + self.Width > mouse[0] > self.X and self.Height + self.Y > mouse[1] > self.Y:
            pygame.draw.rect(surface, color, (self.X, self.Y, self.Width, self.Height))
            if click[0] == 1:
                self.Pressed = True
因此,如果不单击,它将设置为False

你能行

if click[0] == 1:
            self.Pressed = True
else:
            self.Pressed = False

但我记得,
click
有布尔值,所以您只需要

self.Pressed = bool(click[0])

顺便说一句:为了使代码更具可读性,我们只对类使用
CamelCase
名称。对于变量、函数和方法,我们使用
小写
名称


使用
pygame.Rect()
保持按钮大小和位置

self.Pressed = click[0]
然后你可以用鼠标检查

self.rect = pygame.Rect(x, y, width, height)
mouse\u event()
应该只选中事件,而
draw()
应该绘制它-您可以使用
self.rect
来绘制它

if self.rect.collidepoint(mouse):
     self.hover = True
     self.pressed = bool(click[0])
您可以使用它将按钮上的文本居中

if hover:
    pygame.draw.rect(surface, self.color, self.rect)
    surface.blit(self.text, self.text_rect)
else:

另外,如果我帮忙,投票并接受答案。这向社区表明,您在这个答案中获得了成功。
if hover:
    pygame.draw.rect(surface, self.color, self.rect)
    surface.blit(self.text, self.text_rect)
else:
text_rect = text.get_rect()
text_rect.center = self.rect.center     
surface.blit(text, text_rect)