基本上,我想用pygame创建一个按钮并在上面写文本,我成功了。你知道吗
但最后一个按钮(命名为排行榜按钮)不会将image更改为“./image”/鼠标按钮.png当光标在按钮上时。你知道吗
我真想知道为什么会这样。按钮的其余部分很好。你知道吗
import pygame
from pygame.locals import *
import sys
FPS = 60
clock = pygame.time.Clock()
screen = pygame.display.set_mode((800, 700))
screen.fill((255, 255, 255))
pygame.font.init()
pygame.init()
class Button():
def __init__(self, msg, font, x , y, w, h, color):
self.msg = msg
self.font = font
self.x = x
self.y = y
self.w = w
self.h = h
self.color = color
def createButton(self):
(mouseX, mouseY) = pygame.mouse.get_pos()
if((mouseX >= self.x and mouseY <= self.x + self.w) and (mouseY >= self.y and mouseY <= self.y + self.h)):
button = pygame.image.load("./image/mouseOnButton.png")
else:
button = pygame.image.load("./image/button.png")
screen.blit(button, (self.x, self.y))
text = pygame.font.SysFont(self.font, 32)
textSurface = text.render(self.msg.encode("utf-8"), True, self.color)
screen.blit(textSurface, (self.x + self.w / len(self.msg), self.y + self.h / 2))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == KEYDOWN:
if(event.key == pygame.K_F4 and pygame.KMOD_ALT):
sys.exit()
localButton = Button("Local Play", "./font/NanumSquareRoundEB.ttf", 325, 200, 150, 75, (255, 255, 255)).createButton()
socketButton = Button("Socket Play", "./font/NanumSquareRoundEB.ttf", 325, 325, 150, 75, (255, 255, 255)).createButton()
howtoButton = Button("How to Play", "./font/NanumSquareRoundEB.ttf", 325, 450, 150, 75, (255, 255, 255)).createButton()
leaderboardButton = Button("Leaderboard", "./font/NanumSquareRoundEB.ttf", 325, 575, 150, 75, (255, 255, 255)).createButton()
pygame.display.update()
clock.tick(FPS)
该问题是由
createButton
方法第二行中的一个输入错误引起的(最好使用pygame.Rect及其冲突检测方法):我建议在while循环之前创建
Button
的实例,并给它们一个draw
和一个handle_event
方法,这样您就可以在while循环内部调用button.draw(screen)
。我已经修改了下面示例中的按钮。注意,通过使用pygame.Rect
s作为blit位置和冲突检测,可以简化代码。您还可以将按钮放入列表中并绘制它们,并在for循环中处理事件,例如for button in button_list: button.draw(screen)
。你知道吗相关问题 更多 >
编程相关推荐