使用 pygame 在 python 中制作按钮

问题描述

我试图制作一个按钮,代码有效,但我试图弄清楚如何使矩形变小并将其移动到左上角,我还想知道如何制作多个按钮。我建议您是否可以在pycharm中运行代码,并将代码放入代码中以更改位置。

按钮代码

import pygame
pygame.init()

win = pygame.display.set_mode((500,500))
win.fill((255,255,255))

#START
class button():
   def __init__(self,color,x,y,width,height,text=''):
       self.color = color
       self.x = x
       self.y = y
       self.width = width
       self.height = height
       self.text = text   


def draw(self,win,outline=None):
    # Call this method to draw the button on the screen
    if outline:
        pygame.draw.rect(win,outline,(self.x - 2,self.y - 2,self.width + 4,self.height + 4),0)

    pygame.draw.rect(win,self.color,(self.x,self.y,self.width,self.height),0)

    if self.text != '':
        font = pygame.font.SysFont('comicsans',60)
        text = font.render(self.text,1,(0,0))
        win.blit(text,(
        self.x + (self.width / 2 - text.get_width() / 2),self.y + (self.height / 2 - text.get_height() / 2)))

def isOver(self,pos):
    # Pos is the mouse position or a tuple of (x,y) coordinates
    if pos[1] > self.x and pos[1] < self.x + self.width:
        if pos[1] > self.y and pos[1] < self.y + self.height:
            return True

def redrawWindow ():
   win.fill((255,255))
   greenButton.draw(win,0))


run = True
greenButton = button((0,0),150,225,250,100,'Start')
while run:
    redrawWindow()
    pygame.display.update()

    for event in pygame.event.get():
          pos = pygame.mouse.get_pos()

    if event.type == pygame.QUIT:
        run = False
        pygame.quit()
        quit()

    if event.type == pygame.MOUSEBUTTONDOWN:
        if greenButton.isOver(pos):
            print('clicked')

    if event.type == pygame.MOUSEMOTION:
        if greenButton.isOver(pos):
            greenButton.color = (0,0)
        else:
            greenButton.color = (0,0)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)