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)
The 'code' you have found online is not that good. All you need to make a button is this. Put this near the beginning of your code:
def Buttonify(Picture, coords, surface):
image = pygame.image.load(Picture)
imagerect = image.get_rect()
imagerect.topright = coords
surface.blit(image,imagerect)
return (image,imagerect)
Put the following in your game loop. Also somewhere in your game loop:
Image = Buttonify('YOUR_PICTURE.png',THE_COORDS_OF_THE_BUTTON'S_TOP_RIGHT_CORNER, THE_NAME_OF_THE_SURFACE)
Also put this in your game loop wherever you have done for event in pygame.event.get
if event.type == MOUSEBUTTONDOWN and event.button == 1:
mouse = pygame.mouse.getpos
if Image[1].collidrect(mouse):
#code if button is pressed goes here
So, buttonify loads the image that will be on the button. This image must be a .jpg file or any other PICTURE file in the same directory as the code. Picture is its name. The name must have .jpg or anything else after it and the name must be in quotation marks. The coords parameter in Buttonify is the top-right coordinate on your screen or window that opens from pygame. The surface is this thing:
blahblahblah = pygame.surface.set_mode((WindowSize))
/|\
|
Surface's Name
So it the function makes something called 'image' which is a pygame surface, it puts a rectangle around it called 'imagerect' (to set it at a location and for the second parameter when blitting,) and then it sets it's location, and blits it on the second to last last line.
The next bit of code makes 'Image' a tuple of both 'image' and 'imagerect.'
The last code has if event.type == MOUSEBUTTONDOWN and event.button == 1:
which basically means if the left mouse button is pressed. This code MUST be in for event in pygame.event.get
. The next line makes mouse a tuple of the mouses position. The last line checks if the mouse collided with Image[1] which as we know is 'imagerect.' The code follows that.
Tell me if I need to explain further.