我已经设置了按钮功能,但是想知道如何在按钮上放置图像而不是文本。
在该类中,属性text =''允许将文本放置在按钮上,但想知道如何更改它以允许图像
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):
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,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 ):
if pos[0] > self.x and pos[0] < self.x + self.width:
if pos[1] > self.y and pos[1] < self.y + self.height:
return True
return False
添加self.image
为__init_
功能为:
self.image = pygame.image.load('image.png') # Make that the image is in the same folder as your python file
而在您的职能,只需blitself.image
而不是text
:
win.blit(self.image, (self.x +(self.width/2 - text.get_width()/2), self.y + (self.height/2 - text.get_height()/2)))
全部一起:
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
self.image = pygame.image.load('image.png')
def draw(self,win,outline=None):
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,0))
win.blit(self.image, (self.x +(self.width/2 - text.get_width()/2), self.y + (self.height/2 - text.get_height()/2)))
def isOver(self, pos ):
if pos[0] > self.x and pos[0] < self.x + self.width:
if pos[1] > self.y and pos[1] < self.y + self.height:
return True
return False
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句