如何解决使用 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 举报,一经查实,本站将立刻删除。