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

时间:2018-01-02 16:19:06

标签: python user-interface button pygame

我正在尝试制作一个带有按钮的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()

1 个答案:

答案 0 :(得分: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()