我正在尝试制作一个pygame,并且无法将命令链接到按钮

问题描述 投票:-1回答:1

我试图制作一个带有按钮的GUI,当玩家将鼠标悬停在按钮上时,这些按钮可以在不打开新窗口的情况下将它们引导到游戏的那个部分。我在下面提供了我的代码。

import pygame, sys, tkinter
from pygame.locals import *

#Initialize pygame and define colours
pygame.init()
white = 255, 255, 255

#Sets the resolution to 640 pixels by 720 pixels and caption for pygame window
DISPLAY_SURF = pygame.display.set_mode((640, 720))
pygame.display.set_caption("The Hunt!")



#Create a clock object
clock = pygame.time.Clock()
FPS = 60

#Define a variable to refer to image
background = pygame.image.load("Startermenu.png")
start = pygame.image.load("PlayGameButton.png")
help = pygame.image.load("HelpButton.png")
credits = pygame.image.load("ShowCreditsButton.png")


#Start main loop
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    DISPLAY_SURF.fill(white)
    DISPLAY_SURF.blit(background,(0,0))
    DISPLAY_SURF.blit(start, (0, 140))
    DISPLAY_SURF.blit(help, (0, 186))
    DISPLAY_SURF.blit(credits, (0, 235))
    pygame.display.update()
python user-interface button pygame
1个回答
0
投票

你需要一个按钮吗?

这是一个按钮类:

class Button(object):
    def __init__(self,x,y,width,height,text_color,background_color,text):
        self.rect=pygame.Rect(x,y,width,height)
        self.image=pygame.draw.rect(screen, background_color,(self.rect),)
        self.x=x
        self.y=y
        self.width=width
        self.height=height
        self.text=text
        self.text_color=text_color

    def check(self):
        #will return if mouse is inside button
        return self.rect.collidepoint(pygame.mouse.get_pos())

    def draw(self):
        #draw button and border 
        drawText(self.text,font,screen,self.x+self.width/2,self.y+self.height/2,self.text_color)                          
        pygame.draw.rect(screen,self.text_color,self.rect,3) 

将其实现到主循环中:

#create a button instance
button=Button(parameters)
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if elif event.type == pygame.MOUSEBUTTONDOWN:
            if start_button.check()==True:
                #what you to do when the user clicks button

    DISPLAY_SURF.fill(white)
    DISPLAY_SURF.blit(background,(0,0))
    DISPLAY_SURF.blit(start, (0, 140))
    DISPLAY_SURF.blit(help, (0, 186))
    DISPLAY_SURF.blit(credits, (0, 235))

    #draw button
    button.draw()

    pygame.display.update()
© www.soinside.com 2019 - 2024. All rights reserved.