【问题标题】:Creating rect Buttons with Pygame [duplicate]使用 Pygame 创建矩形按钮 [重复]
【发布时间】:2016-10-31 05:18:27
【问题描述】:

我正在尝试在 Pygame 中使用 rect 制作按钮。我从红色的退出按钮开始,然后检查按钮的边界框内是否有点击。

    import pygame
"""import nemesis.py;"""

pygame.init();
screen = pygame.display.set_mode((400,300));
pygame.display.set_caption("menu");
menuAtivo = True;

start_button = pygame.draw.rect(screen,(0,0,240),(150,90,100,50));
continue_button = pygame.draw.rect(screen,(0,244,0),(150,160,100,50));
quit_button = pygame.draw.rect(screen,(244,0,0),(150,230,100,50));


pygame.display.flip();


while menuAtivo:
    for evento in pygame.event.get():
        print(evento);
        if evento.type == pygame.MOUSEBUTTONDOWN:
            if pygame.mouse.get_pos() >= (150,230):
                if pygame.mouse.get_pos() <= (250,280):
                        pygame.quit();
                    

【问题讨论】:

    标签: python button pygame


    【解决方案1】:

    在 pygame 中使用 rects 时,最好使用内置的碰撞检测。 这是一个示例代码,希望它可以帮助您解决问题。

    在此之前,尽管我想提一下,您应该使用 while 循环渲染/绘制对象,否则不会显示。

    import pygame
    import sys
    
    
    def main():
        pygame.init()
        clock = pygame.time.Clock()
        fps = 60
        size = [200, 200]
        bg = [255, 255, 255]
    
        screen = pygame.display.set_mode(size)
    
        button = pygame.Rect(100, 100, 50, 50)  # creates a rect object
        # The rect method is similar to a list but with a few added perks
        # for example if you want the position of the button you can simpy type
        # button.x or button.y or if you want size you can type button.width or
        # height. you can also get the top, left, right and bottom of an object
        # with button.right, left, top, and bottom
    
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return False
    
                if event.type == pygame.MOUSEBUTTONDOWN:
                    mouse_pos = event.pos  # gets mouse position
    
                    # checks if mouse position is over the button
    
                    if button.collidepoint(mouse_pos):
                        # prints current location of mouse
                        print('button was pressed at {0}'.format(mouse_pos))
    
            screen.fill(bg)
    
            pygame.draw.rect(screen, [255, 0, 0], button)  # draw button
    
            pygame.display.update()
            clock.tick(fps)
    
        pygame.quit()
        sys.exit
    
    
    if __name__ == '__main__':
        main()
    

    【讨论】:

      【解决方案2】:

      在 pygame(在 python 中)上创建按钮的另一种好方法是在 Mac 或 Linux 上安装名为 pygame_widgets(pip3 install pygame_widgets)的软件包,在 Windows 上安装(pip install pygame_widgets)。并且还要确保你已经安装了 pip,否则它是行不通的。

      # Importing Modules
      import pygame as pg
      import pygame_widgets as pw
      # creating screen
      pg.init()
      screen = pg.display.set_mode((800, 600))
      running = True
      button = pw.Button(
              screen, 100, 100, 300, 150, text='Hello',
              fontSize=50, margin=20,
              inactiveColour=(255, 0, 0),
              pressedColour=(0, 255, 0), radius=20,
              onClick=lambda: print('Click')
           )
      
      while running:
            events = pg.event.get()
            for event in events:
                 if event.type == pg.QUIT:
                      running = False
            button.listen(events)
            button.draw()
            pg.display.update()
      

      希望对您有所帮助。

      【讨论】:

      • 遗憾的是,它仅适用于 3 以上的 python 版本。希望这会有所帮助。再见
      【解决方案3】:

      TKS 伙计们,

      这是我的答案:

      import pygame
      
      
      pygame.init();
      screen = pygame.display.set_mode((400,300));
      pygame.display.set_caption("menu");
      menuAtivo = True;
      
      start_button = pygame.draw.rect(screen,(0,0,240),(150,90,100,50));
      continue_button = pygame.draw.rect(screen,(0,244,0),(150,160,100,50));
      quit_button = pygame.draw.rect(screen,(244,0,0),(150,230,100,50));
      
      
      pygame.display.flip();
      
      def startGame():
          screen.fill((0,0,0));
          pygame.display.flip();
          import nemesis.py;
      
      while menuAtivo:
          for evento in pygame.event.get():
              print(evento);
              if evento.type == pygame.MOUSEBUTTONDOWN:
                  if pygame.mouse.get_pos()[0] >= 150 and pygame.mouse.get_pos()[1] >= 230:
                      if pygame.mouse.get_pos()[0] <= 250 and pygame.mouse.get_pos()[1] <= 280:
                              pygame.quit();
                  if pygame.mouse.get_pos()[0] >= 150 and pygame.mouse.get_pos()[1] >= 90:
                      if pygame.mouse.get_pos()[0] <= 250 and pygame.mouse.get_pos()[1] <= 140:
                              startGame();
      

      【讨论】:

        【解决方案4】:

        我认为您的代码中的主要问题是您将 pygame.mouse.get_pos() 直接与元组进行比较,这是模棱两可的。您应该尝试分别测试 x 然后 y:

        while menuAtivo:
        for evento in pygame.event.get():
            print(evento);
            if evento.type == pygame.MOUSEBUTTONDOWN:
                if pygame.mouse.get_pos()[0] >= 150 and pygame.mouse.get_pos()[1] >= 230:
                    if pygame.mouse.get_pos()[0] <= 250 and pygame.mouse.get_pos()[1] <= 280:
                            pygame.quit();
        

        【讨论】:

          【解决方案5】:

          我已经在上面提供了答案。这是我没有模块 pygame_widgets 的另一个答案:

          import pygame 
          import sys 
            
            
          # initializing the constructor 
          pygame.init() 
            
          # screen resolution 
          res = (720,720) 
            
          # opens up a window 
          screen = pygame.display.set_mode(res) 
            
          # white color 
          color = (255,255,255) 
            
          # light shade of the button 
          color_light = (170,170,170) 
            
          # dark shade of the button 
          color_dark = (100,100,100) 
            
          # stores the width of the 
          # screen into a variable 
          width = screen.get_width() 
            
          # stores the height of the 
          # screen into a variable 
          height = screen.get_height() 
            
          # defining a font 
          smallfont = pygame.font.SysFont('Corbel',35) 
            
          # rendering a text written in 
          # this font 
          text = smallfont.render('quit' , True , color) 
            
          while True: 
                
              for ev in pygame.event.get(): 
                    
                  if ev.type == pygame.QUIT: 
                      pygame.quit() 
                        
                  #checks if a mouse is clicked 
                  if ev.type == pygame.MOUSEBUTTONDOWN: 
                        
                      #if the mouse is clicked on the 
                      # button the game is terminated 
                      if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40: 
                          pygame.quit() 
                            
              # fills the screen with a color 
              screen.fill((60,25,60)) 
                
              # stores the (x,y) coordinates into 
              # the variable as a tuple 
              mouse = pygame.mouse.get_pos() 
                
              # if mouse is hovered on a button it 
              # changes to lighter shade  
              if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40: 
                  pygame.draw.rect(screen,color_light,[width/2,height/2,140,40]) 
                    
              else: 
                  pygame.draw.rect(screen,color_dark,[width/2,height/2,140,40]) 
                
              # superimposing the text onto our button 
              screen.blit(text , (width/2+50,height/2)) 
                
              # updates the frames of the game 
              pygame.display.update()
          

          如果无法在您的 python 版本中安装 pygame_widgets (pip install pygame_widgets) 模块,希望这会有所帮助。

          【讨论】:

            【解决方案6】:

            这是我的解决方案

            class button():
                def __init__(self, color, x,y,width,height, text=''):
                    self.color = color
                    self.x = x
                    self.y = y
                    self.width = width
                    self.height = height
                    self.text = text
            
                def draw(self,win,outline=None):
                    #Call this method to draw the button on the screen
                    if outline:
                        pygame.draw.rect(win, outline, (self.x-2,self.y-2,self.width+4,self.height+4),0)
                        
                    pygame.draw.rect(win, self.color, (self.x,self.y,self.width,self.height),0)
                    
                    if self.text != '':
                        font = pygame.font.SysFont('comicsans', 60)
                        text = font.render(self.text, 1, (0,0,0))
                        win.blit(text, (self.x + (self.width/2 - text.get_width()/2), self.y + (self.height/2 - text.get_height()/2)))
            
                def isOver(self, pos):
                    #Pos is the mouse position or a tuple of (x,y) coordinates
                    if pos[0] > self.x and pos[0] < self.x + self.width:
                        if pos[1] > self.y and pos[1] < self.y + self.height:
                            return True
                        
                    return False
            

            【讨论】:

            • 代码转储不能提供好的答案。你应该解释如何为什么这可以解决他们的问题。我推荐阅读,“How do I write a good answer?"
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2019-01-08
            • 1970-01-01
            • 1970-01-01
            • 2016-04-27
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多