[英]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)
以下是每个参数的含义:
只需使用不同的矩形位置和不同的变量名称重复相同的代码即可。
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.