import sys
import pygame
from pygame.locals import *
pygame.font.init()
font1 = pygame.font.SysFont('kaiti', 25)
class Button:
def __init__(self, text, color, x, y, width, height, font, count):
self.x = x
self.y = y
self.count = 0
self.width = width
self.height = height
self.color = color
self.text = text
self.font = font
self.surface = font.render(text, True, color)
self.body = pygame.Rect(self.x, self.y, self.width, self.height)
def draw(self, screen):
r, g, b = (255, 255, 0) if self.count % 2 == 0 else (0, 255, 255)
pygame.draw.rect(screen, (r, g, b), (self.x + 1, self.y + 1, self.width - 3, self.height - 3), 0)
screen.blit(self.surface, (self.body.x + (self.body.width - self.surface.get_width()) // 2,
self.y + (self.body.height - self.surface.get_height()) // 2))
def check_click(self, event):
x_match = self.x <= event.pos[0] <= self.x + self.width
y_match = self.y <= event.pos[1] <= self.y + self.height
if x_match and y_match and event.type == pygame.MOUSEBUTTONDOWN:
self.count += 1
self.surface = self.font.render(self.text, True, self.color) # 更新文字渲染
btnfj = Button("风机", 'red', 482, 280, 70, 40, font1, 0)
btnsb = Button("水泵", 'red', 40, 280, 70, 40, font1, 0)
if __name__ == "__main__":
pygame.init()
size = width, height = 800, 600
screen = pygame.display.set_mode(size)
pygame.display.set_caption("生产线")
framerate = pygame.time.Clock()
while True:
framerate.tick(30)
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
btnfj.check_click(event)
btnsb.check_click(event)
screen.fill((0, 0, 0))
btnfj.draw(screen)
btnsb.draw(screen)
pygame.display.update()