如何在 python/pygame 中制作按钮? [英] How to make buttons in python/pygame?
问题描述
我正在 pygame 中制作游戏,并且在第一个屏幕上我希望有一些按钮,您可以按这些按钮 (i) 开始游戏,(ii) 加载带有说明的新屏幕,以及 (iii) 退出程序.
I'm making a game in pygame and on the first screen I want there to be buttons that you can press to (i) start the game, (ii) load a new screen with instructions, and (iii) exit the program.
我在网上找到了用于按钮制作的这段代码,但我不太明白(我不太擅长面向对象编程).如果我能得到一些关于它在做什么的解释,那就太好了.另外,当我使用它并尝试使用文件路径在我的计算机上打开文件时,出现错误 sh: filepath :Permission denied ,我不知道如何解决.
I've found this code online for button making, but I don't really understand it (I'm not that good at object oriented programming). If I could get some explanation as to what it's doing that would be great. Also, when I use it and try to open a file on my computer using the file path, I get the error sh: filepath :Permission denied, which I don't know how to solve.
#load_image is used in most pygame programs for loading images
def load_image(name, colorkey=None):
fullname = os.path.join('data', name)
try:
image = pygame.image.load(fullname)
except pygame.error, message:
print 'Cannot load image:', fullname
raise SystemExit, message
image = image.convert()
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0,0))
image.set_colorkey(colorkey, RLEACCEL)
return image, image.get_rect()
class Button(pygame.sprite.Sprite):
"""Class used to create a button, use setCords to set
position of topleft corner. Method pressed() returns
a boolean and should be called inside the input loop."""
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = load_image('button.png', -1)
def setCords(self,x,y):
self.rect.topleft = x,y
def pressed(self,mouse):
if mouse[0] > self.rect.topleft[0]:
if mouse[1] > self.rect.topleft[1]:
if mouse[0] < self.rect.bottomright[0]:
if mouse[1] < self.rect.bottomright[1]:
return True
else: return False
else: return False
else: return False
else: return False
def main():
button = Button() #Button class is created
button.setCords(200,200) #Button is displayed at 200,200
while 1:
for event in pygame.event.get():
if event.type == MOUSEBUTTONDOWN:
mouse = pygame.mouse.get_pos()
if button.pressed(mouse): #Button's pressed method is called
print ('button hit')
if __name__ == '__main__': main()
感谢任何能帮助我的人.
Thank you to anyone who can help me.
推荐答案
我没有给你的代码示例,但我的做法是:
I don't have a code example for you, but how I would do it is to:
- 创建一个按钮类,将按钮上的文本作为构造函数参数
- Make a Button class, with the text to go on the button as a constructor argument
- 创建一个 PyGame 表面,无论是图像还是填充的矩形
- 使用 Pygame 中的 Font.Render 内容在其上渲染文本
这与您的示例正在执行的操作相似,尽管仍然不同.
That is similar to what your example is doing, although different still.
这篇关于如何在 python/pygame 中制作按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!