繁体   English   中英

如何在 pygame 中制作多个按钮?

[英]How do i make more than one button in pygame?

我已经制作了这段代码,但是如果我复制它或其他任何东西,我将无法制作更多按钮,所以无论如何我可以以我设置此代码的方式获得更多按钮吗? 是否可以放入 def display_button() 并在循环中调用它?

def Main():

pygame.font.init()
font = pygame.font.Font(None, 25)
my_font = pygame.font.SysFont("segoe print", 16)

button_surf = pygame.Surface((60, 40))
button_rect = button_surf.get_rect()
button_surf.fill(WHITE)
button_rect.center = (500, 750)
txt_surf = my_font.render("LEFT", 1, BLACK)
txt_rect = txt_surf.get_rect(center=(30,20))
button_surf.blit(txt_surf, txt_rect)


Seconds = 0
Frame=0

gameExit = False
while not gameExit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    Screen.fill(BLACK)
    Screen.blit(button_surf, button_rect)

那是我的代码

您应该为按钮创建一个单独的功能:

def button(x, y, w, h, inactive, active, action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    if x + w > mouse[0] > x and y + h > mouse[1] > y:
        gameDisplay.blit(active, (x, y))
        if click[0] == 1 and action is not None:
            action()
    else:
        gameDisplay.blit(inactive, (x, y))

完成后,您可以这样调用它:

#For Example
button(100, 350, 195, 80, startBtn, startBtn_hover, game_loop)

以下是每个参数的含义:

  • x:按钮的 x 坐标
  • y: 按钮的 y 坐标
  • w:按钮的宽度
  • h:按钮的高度
  • active:鼠标悬停在按钮上时的图片
  • inactive:按钮空闲时的图片
  • action:按钮被点击时执行的函数

只需使用不同的矩形位置和不同的变量名称重复相同的代码即可。

button_surf2 = pygame.Surface((60, 40))
button_rect2 = button_surf.get_rect()
button_surf2.fill(WHITE)
button_rect2.center = (600, 850)
txt_surf2 = my_font.render("LEFT", 1, BLACK)
txt_rect2 = txt_surf2.get_rect(center=(30,20))
button_surf2.blit(txt_surf2, txt_rect2)

或者,如果你想让它更整洁一点,你可以制作一个按钮类。

def Button:
    def __init__(self, width, height, center, text):
        self.surface = pygame.Surface((width, height))
        self.rect = self.surface.get_rect()
        self.surface.fill(WHITE)
        self.rect.center = center
        self.textSurf = my_font.render(text, 1, BLACK)
        self.textRect = self.textSurf.get_rect(center = (30, 20))
        self.surf.blit(self.textSurf, self.textRect)

然后,您应该列出所有按钮,并在要绘制或检查点击时遍历它们。

我认为你应该使用

我正在使用这些,这是示例:

buttons = pygame.sprite.Group()
picnames = ["Play","Quit"]
place = y/2 - 10 * (len(picnames) - 1) - 8
for picname in picnames:
    button = pygame.sprite.Sprite()
    button.name = picname
    button.image = pygame.image.load("pic/" + picname + ".PNG").convert_alpha()
    button.rect = button.image.get_rect()
    button.rect.center = (x/2, place)
    place += 20
    buttons.add(button)

buttons.draw(screen)

是我的全部代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM