Struggling with multiple programming languages? No worries. OurCode Converter has got you covered. Give it a go!
In this article, we are going to make a button class inpygame in Python which can be utilized in different ways. We make it, so the button calls a custom function when pressed. We also enable it to support "pressed calling" and "one-shot" pressing. Last but not least, we will build a system for multiple buttons, so they dynamically get drawn without having to add them to a list manually.Let us start!
Before we make theButton class we need to set up a viablepygame window, therefore we importsys andpygame.sys will be needed later to shut down the window. After that, we initiatepygame with thepygame.init() function. After defining thefps we make a newpygame clock.
We continue by making the screen. After that, we load a font which we will later use in the buttons, you can use whatever font you want, but I'll chooseArial for this tutorial. At last, we make a list calledobjects. We later need this for the buttons and the dynamic drawing.
# Importsimport sysimport pygame# Configurationpygame.init()fps = 60fpsClock = pygame.time.Clock()width, height = 640, 480screen = pygame.display.set_mode((width, height))font = pygame.font.SysFont('Arial', 40)objects = []Now we can finally start with theButton class. We code the__init__() to take several arguments: thex andy coordinates, thewidth and theheight, the text in the button, the function which will be called, and whether the button will be pressed once.
We map all these information to variables in the object. We also define some colors for the three states the button will have;'normal','hover', and'pressed'.
class Button(): def __init__(self, x, y, width, height, buttonText='Button', onclickFunction=None, onePress=False): self.x = x self.y = y self.width = width self.height = height self.onclickFunction = onclickFunction self.onePress = onePress self.alreadyPressed = False self.fillColors = { 'normal': '#ffffff', 'hover': '#666666', 'pressed': '#333333', }After we set up the variables, we make thebuttonSurface, and thebuttonRect. Here we use the values we defined above.
We also make a surface that contains thebuttonText. Here we use thefont variable we defined earlier to call therender() method on it:
self.buttonSurface = pygame.Surface((self.width, self.height)) self.buttonRect = pygame.Rect(self.x, self.y, self.width, self.height) self.buttonSurf = font.render(buttonText, True, (20, 20, 20))Last but not least, we append the object itself to theobjects list. Later we will loop over this list to call all theprocess() functions from the buttons.
objects.append(self)Now we turn to theprocess() method. This will be called every frame. That's why we are here checking for the mouse hover and click.
We start by getting the mouse position. After that, we fill thebuttonSurface with our'normal' color, this may be an unnecessary step because it may be recolored depending on the hover or click.
Then we check whether the mouse position is inside the rect or not. If this evaluates toTrue, we set the color to the'hover' color.
Next, we check if the left mouse button has been pressed with thepygame.mouse.get_pressed() method. This method will return a tuple representing the pressed states of the three mouse buttons. The first one is the left button, which is what we need. If this is also evaluated to beTrue we once again fill thebuttonSurface with the'pressed' color.
Now, if we set theonePress variable toFalse (which is the default) then theonclickFunction(), which we later defined, will be called. This means it will be called once when the mouse clicks on the button. For this to work, we also need analreadyPressed attribute in the object, which is set toTrue when we press and is set toFalse when we release it.
But maybe you want to call as long as you press it down. That is what the firstif statement is for. When we setonePress toTrue this happens.
def process(self): mousePos = pygame.mouse.get_pos() self.buttonSurface.fill(self.fillColors['normal']) if self.buttonRect.collidepoint(mousePos): self.buttonSurface.fill(self.fillColors['hover']) if pygame.mouse.get_pressed(num_buttons=3)[0]: self.buttonSurface.fill(self.fillColors['pressed']) if self.onePress: self.onclickFunction() elif not self.alreadyPressed: self.onclickFunction() self.alreadyPressed = True else: self.alreadyPressed = FalseThe last thing we do in theprocess() method is blitting the text onto thebuttonSurface and then this surface onto thescreen.
self.buttonSurface.blit(self.buttonSurf, [ self.buttonRect.width/2 - self.buttonSurf.get_rect().width/2, self.buttonRect.height/2 - self.buttonSurf.get_rect().height/2 ]) screen.blit(self.buttonSurface, self.buttonRect)Learn also: How to Change Text Color in Python.
Now that we have made theButton class, we can make a little function that will be passed to the class constructor. In our example, it just prints out"Button Pressed".
Let's make two button objects. We don't have to save them into a variable or something like that because the constructor already does that:
def myFunction(): print('Button Pressed')Button(30, 30, 400, 100, 'Button One (onePress)', myFunction)Button(30, 140, 400, 100, 'Button Two (multiPress)', myFunction, True)We first fill the screen with a dark grey in the main loop. After that, we enable the user to stop the game with the littlex at the top right of the window.
In theobjects loop, we go over every object and call itsprocess() function. In our example, this list will have two button objects. After that, we simplyflip() the display and call thetick() method on theclock object frompygame.
while True: screen.fill((20, 20, 20)) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() for object in objects: object.process() pygame.display.flip() fpsClock.tick(fps)The following GIF shows how the button works:
Awesome! Now you know how to make a button inpygame, see how you can customize the buttons by editing the variables we've set in this tutorial.
You can get the complete codehere.
Here are some related tutorials:
Happy coding ♥
Found the article interesting? You'll love ourPython Code Generator! Give AI a chance to do the heavy lifting for you. Check it out!
View Full Code Build My Python CodeGot a coding query or need some guidance before you comment? Check out thisPython Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!
