1

So i have the button functions below which are called as follows (pygame):

button("Play", 50, 500, 100, 50, RED, LIGHT_RED, action = "Play")

I use this for the main menu which is working great, but as well as text on rectangles that are clickable I want there to also be a couple of buttons which are images, which are also clickable. I tried changing the first argument in button() to filename and inserting the name of the file in the function call, but I get an 'Argument must be bytes or unicode' error. Any ideas how I can alter this function to create a similar imageButton() function?

def text_to_button(msg, color, buttonx, buttony, buttonwidth, buttonheight, size = "small"):
    textSurf, textRect = text_objects(msg,color,size)
    textRect.center = ((buttonx+(buttonwidth/2)), buttony+(buttonheight/2))
    PLAYSURF.blit(textSurf, textRect)

def message_to_screen(msg, color, y_displace = 0, size = "small"):
    textSurf, textRect = text_objects(msg, color, size)
    textRect.center = (WIDTH / 2), (HEIGHT / 2) + y_displace
    PLAYSURF.blit(textSurf, textRect)

def text_objects(text,color,size):
    if size == "small":
        textSurface = smallfont.render(text, True, color)
    elif size == "medium":
        textSurface = medfont.render(text, True, color)
    elif size == "large":
        textSurface = largefont.render(text, True, color)

    return textSurface, textSurface.get_rect()

def button(text, x, y, width, height, inactive_color, active_color, action = None):
    cur = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()    
    if x + width > cur[0] > x and y + height > cur[1] > y:
        pygame.draw.rect(PLAYSURF, active_color, (x, y, width, height))
        if click[0] == 1 and action != None:
            if action == "Quit":
                pygame.quit()
                quit()
            if action == "Play":
                main()
            if action == "Settings":
                pass
            if action == "Shop":
                pass
            if action == "Pause":
                pause()                
    else:
        pygame.draw.rect(PLAYSURF, inactive_color, (x, y, width, height))        
    text_to_button(text, BLACK, x, y, width, height)

Thanks.

  • Here are a few more ways to implement buttons in pygame: https://stackoverflow.com/a/47664205/6220679 I recommend the object-oriented solution with the `Button` class. – skrx Feb 01 '18 at 08:10

1 Answers1

1

This would be more appropriate for comment, but I can't write one so, I'm writing an answer.

I use another module "pygbutton" for buttons. This module does what exactly you are trying to do. There is a source code for the button class at the link . It would help to just use the module, or having look at the code should help you create you're own.

dkato
  • 895
  • 10
  • 28
Inyoung Kim 김인영
  • 1,434
  • 1
  • 17
  • 38