How to make buttons in python / pygame?

I am making a game in pygame, and on the first screen I want there to be buttons that you can click to (i) launch the game, (ii) load a new screen with instructions and (iii) exit the program.

I found this code online for creating buttons, but I don’t understand it (I am not so good at object-oriented programming). If I could get any explanation as to what he is doing, that would be great. Also, when I use it and try to open the file on my computer using the file path, I get the sh: filepath: Permission denied error, which I do not 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 pressed method is called print ('button hit') if __name__ == '__main__': main() 

Thanks to everyone who can help me.

+6
source share
4 answers

I have no code for you, but how would I do it:

  • Make Button class, text should be included as an argument to the constructor
    • Create a PyGame surface, be it an image or a filled Rect
    • Change the text on it using the Font.Render material in Pygame
  • Blit to game screen, save this rectangle.
  • Check by clicking with the mouse to see mouse.get_pos (), the coordinate in the rectangle corresponds to which it returns by pressing the button on the main surface.

This is similar to what your example does, although it is still different.

+12
source

The "code" you found on the Internet is not so good. All you need to do is a button. Put this next to 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 into 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 do 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. A picture is his name. The name must have .jpg or something 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. A surface is a thing:

 blahblahblah = pygame.surface.set_mode((WindowSize)) /|\ | Surface Name 

So the function does something called an “image”, which is the surface of the piggy, it puts a rectangle around it called “imagerect” (to set it in place for the second parameter when blitting), and then it sets its location and brings him on the second and last last line.

The next bit of code makes the “image” a tuple of both the “image” and the “imagerect”.

The last code has if event.type == MOUSEBUTTONDOWN and event.button == 1: which basically means that the left mouse button is pressed. This code MUST be in for event in pygame.event.get . The next line makes the mouse a tuple of mouse position. The last line checks if the mouse has collided with Image [1], which, as we know, is "imagerect". The code follows this.

Tell me if I need to explain further.

0
source

So, you have to create a function called button that receives 8 parameters. 1) Button message 2) X position of the upper left corner of the button 3) Y position of the upper left corner of the button 4) Width of the button 5) Height of the button 6) Inactive color (background color) 7) Active color (color on hover) 8) Name of the action, which you want to perform

 def button (msg, x, y, w, h, ic, ac, action=None ): mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() if (x+w > mouse[0] > x) and (y+h > mouse[1] > y): pygame.draw.rect(watercycle, CYAN, (x, y, w, h)) if (click[0] == 1 and action != None): if (action == "Start"): game_loop() elif (action == "Load"): ##Function that makes the loading of the saved file## elif (action == "Exit"): pygame.quit() else: pygame.draw.rect(watercycle, BLUE, (x, y, w, h)) smallText = pygame.font.Font("freesansbold.ttf", 20) textSurf, textRect = text_objects(msg, smallText) textRect.center = ( (x+(w/2)), (y+(h/2)) ) watercycle.blit(textSurf, textRect) 

So, when you create a game loop and you call the button function:

("Start", 600, 120, 120, 25, BLUE, CYAN, "Start")

0
source

Here is the class for the button that I created many years ago: https://www.dropbox.com/s/iq5djllnz0tncc1/button.py?dl=0 This button is the style of Windows 7, as far as I remember, and I could not verify it recently, because I don't have pygame on the computer that I use. Hope this helps!

0
source

Source: https://habr.com/ru/post/913288/


All Articles