I'll start with simply copy and pasting my huge chunk of code:
# Libraries #
import pygame
from pygame.locals import *
import ResolutionMenu
# Classes #
class GuiSettings:
def __init__(self):
self.TextSize = 20
self.button_color = (35, 65, 145)
self.button_color_hover = (70, 105, 150)
class Button():
def __init__(self, x, y, width, height, outline, settings, text = "", action = None):
self.x = x
self.y = y
self.width = width
self.height = height
self.text = text
self.settings = settings
self.action = action
self.outline = outline
def draw(self, screen, outline = None):
if self.outline:
pygame.draw.rect(screen, self.outline, (self.x - 2, self.y - 2, self.width + 4, self.height + 4), 0)
color = self.settings.button_color if not self.isOver(pygame.mouse.get_pos()) else self.settings.button_color_hover
pygame.draw.rect(screen, color, (self.x, self.y, self.width, self.height), 0)
if self.text != "":
font = pygame.font.SysFont('segoeuisemibold', self.settings.TextSize)
text = font.render(self.text, 1, (0, 0, 0))
screen.blit(text, (self.x + (self.width / 2 - text.get_width() / 2), self.y + (self.height / 2 - text.get_height() / 2)))
def update(self, events):
for event in events:
if event.type == pygame.MOUSEBUTTONDOWN and self.isOver(pygame.mouse.get_pos()) and self.action:
self.action()
def isOver(self, pos):
if pos[0] > self.x and pos[0] < self.x + self.width:
if pos[1] > self.y and pos[1] < self.y + self.height:
return True
return False
# Variables #
settings = GuiSettings()
Click = False
Clock = pygame.time.Clock()
H, W = ResolutionMenu.resolution
pygame.init()
pygame.display.set_caption("Main Menu")
font = pygame.font.SysFont(None, settings.TextSize)
screen = pygame.display.set_mode((ResolutionMenu.resolution))
# Functions #
def draw_text_center(text, font, colour, surface):
textobj = font.render(text, 1, colour)
textrect = textobj.get_rect()
textrect.center = ((H / 2), (W / 10))
surface.blit(textobj, textrect)
def draw_text(text, font, colour, surface, XandY):
textobj = font.render(text, 1, colour)
textrect = textobj.get_rect()
textrect.topleft = (XandY)
surface.blit(textobj, textrect)
def MainMenu():
while True:
if ResolutionMenu.resolution == (800, 600):
screen.fill ((0, 0, 0))
draw_text_center("Main Menu Navigation", font, (255, 255, 255), screen)
mx, my = pygame.mouse.get_pos()
button1 = pygame.Rect((W/10), (H/5), (W/3), (H/15))
button2 = pygame.Rect((W/10), (H/2), (W/3), (H/15))
if button1.collidepoint((mx, my)):
if Click:
game()
if button2.collidepoint((mx, my)):
if Click:
OptionsMenu()
pygame.draw.rect(screen, (255, 0, 0), button1)
pygame.draw.rect(screen, (255, 0, 0,), button2)
Click = False
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
if event.type == MOUSEBUTTONDOWN:
if event.button == 1:
Click = True
pygame.display.update()
Clock.tick(60)
def game():
running = True
while running:
screen.fill((0,0,0))
draw_text('Test 1', font, (255, 255, 255), screen, (20, 20))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
pygame.display.update()
Clock.tick(60)
def OptionsMenu():
screen = pygame.display.set_mode((800, 600))
settings = GuiSettings()
buttons = [
Button(100, 150, 200, 50, (0, 0, 0), settings, "Set Text Size: 14", lambda: settings.__setattr__('TextSize', 14)),
Button(500, 150, 200, 50, (0, 0, 0), settings, "Set Text Size: 16", lambda: settings.__setattr__('TextSize', 16)),
Button(100, 300, 200, 50, (0, 0, 0), settings, "Set Text Size: 18", lambda: settings.__setattr__('TextSize', 18)),
Button(500, 300, 200, 50, (0, 0, 0), settings, "Set Text Size: 20", lambda: settings.__setattr__('TextSize', 20))
]
running = True
while running:
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
return
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
for button in buttons:
button.update(events)
screen.fill((100, 100, 100))
for button in buttons:
button.draw(screen)
pygame.display.flip()
MainMenu()
So as you can see, recently I've been trying to make a main menu navigation panel for a game, and all is going well so far. I have stumbled into a problem, however.
The problem is thus: I have created a class of which holds the settings for text size, the button colour and the button hover colour (the colour of the button will change when the mouse pos is inside of the button's area).
class GuiSettings:
def __init__(self):
self.TextSize = 20
self.button_color = (35, 65, 145)
self.button_color_hover = (70, 105, 150)
This works completely fine when I'm inside of the OptionMenu() function, but when breaking that function, by pressing esc and returning to the MainMenu() function, the text size of the "Main Menu Navigation" text (Code below) doesn't change, despite using the 'settings.TextSize' as the size variable. I'm not sure why this is seeing as on the options menu uses a lambda function to change the value of the text size.
buttons = [
Button(100, 150, 200, 50, (0, 0, 0), settings, "Set Text Size: 14", lambda: settings.__setattr__('TextSize', 14)),
Button(500, 150, 200, 50, (0, 0, 0), settings, "Set Text Size: 16", lambda: settings.__setattr__('TextSize', 16)),
Button(100, 300, 200, 50, (0, 0, 0), settings, "Set Text Size: 18", lambda: settings.__setattr__('TextSize', 18)),
Button(500, 300, 200, 50, (0, 0, 0), settings, "Set Text Size: 20", lambda: settings.__setattr__('TextSize', 20))
]
Sorry that this has been such a long question, thank you for reading and I hope someone better at this than me can give me some help.
You create the font object before the main application loop with the font size settings.TextSize. This font object doesn't magically change when you change the settings.TextSize afterwards. The font size is used to rasterize the glyphs in the font. You need to create a new font object with a new size after the function OptionsMenu is left.
Furthermore you need to use the global statement, since font and settings are variables in global namespace.
def MainMenu():
global font # font is a variable in global namespace
while True:
if ResolutionMenu.resolution == (800, 600):
# [...]
if button2.collidepoint((mx, my)):
if Click:
OptionsMenu()
# create new font with new size
font = pygame.font.SysFont(None, settings.TextSize)
# [...]
def OptionsMenu():
global settings # settings is a variable in global namespace
screen = pygame.display.set_mode((800, 600))
# settings = GuiSettings() # <--- DELETE use the existing object instead
# [...]
Related
The following code works, but it looks a bit kludgy to me. I wander if there is a better way to write it than my approach. Also its resolution is far too high. If anyone has any ideas as to a better approach and how to slow down the resolution, I would love to hear it. Thank you!
import pygame as pg
from random import randint###RANDOM LIBRARY
pg.init()
screen = pg.display.set_mode((640, 480))
FONT = pg.font.Font(None, 36)
BACKGROUND_COLOR = (37, 225, 192)
BLUE = (0, 0, 199)
GRAY = (0, 0, 55)
#Rectangle variables.
measure_rect = pg.Rect(200, 40, 100, 400)
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
random_bar=randint(33,34)#Manipulation of bar graph.
value_print=random_bar
length = random_bar*4
random_bar = 100 - random_bar
top = 40+(random_bar*4)
screen.fill(BACKGROUND_COLOR)
pg.draw.rect(screen, BLUE, (200, top, 100, length))
pg.draw.rect(screen, GRAY, measure_rect, 2)
txt = FONT.render(str(round(value_print, 2)), True, GRAY)
screen.blit(txt, (120, 20))
pg.display.flip()
pg.quit()
I recommend to implement a Bar class:
import pygame as pg
from random import randint###RANDOM LIBRARY
pg.init()
screen = pg.display.set_mode((640, 480))
FONT = pg.font.Font(None, 36)
BACKGROUND_COLOR = (37, 225, 192)
BLUE = (0, 0, 199)
GRAY = (0, 0, 55)
class Bar():
def __init__(self, rect, bar = BLUE, outline = GRAY):
self.rect = pg.Rect(rect)
self.bar = bar
self.outline = outline
self.value = 0
def draw(self, surf):
length = round(self.value * self.rect.height / 100)
top = self.rect.height - length
pg.draw.rect(surf, self.bar, (self.rect.x, self.rect.y + top, self.rect.width, length))
pg.draw.rect(surf, self.outline, self.rect, 2)
txt = FONT.render(str(round(self.value, 2)), True, GRAY)
txt_rect = txt.get_rect(topright = (self.rect.x - 10, self.rect.y))
screen.blit(txt, txt_rect)
bar = Bar((200, 40, 100, 400))
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
bar.value = randint(33, 34)
screen.fill(BACKGROUND_COLOR)
bar.draw(screen)
pg.display.flip()
pg.quit()
This question already has answers here:
How to Center Text in Pygame
(6 answers)
Pygame: Centering text system font text
(1 answer)
Closed 1 year ago.
So I just wanna get some words written in the centre of the rectangles like 'Play Game' or something like that and I'm not exactly sure what to really do.
def drawText(text, x, y, fSize):
screen_text = pygame.font.SysFont("Calibri", fSize, True).render(text, True, (0, 0, 0))
rect = screen_text.get_rect()
rect.center = ((screen_side_length // 2) + x), ((screen_side_length // 2) + y)
screen.blit(screen_text, rect)
def main_menu():
user_choice = None
while user_choice == None:
screen.fill((255, 255, 255))
drawText('main menu', 0, 0, 20)
x, y = pygame.mouse.get_pos()
button_1 = pygame.Rect(50, 100, 200, 50)
button_2 = pygame.Rect(50, 200, 200, 50)
pygame.draw.rect(screen, (255, 0, 0), button_1)
pygame.draw.rect(screen, (255, 0, 0), button_2)
click = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
click = True
pygame.display.update()
clock.tick(15)
return user_choice
You have to set the center of the text rectangle:
font = pygame.font.SysFont("Calibri", fSize, True)
def drawTextCenter(text, centerx, centery, fSize):
font.render(text, True, (0, 0, 0))
rect = screen_text.get_rect(center = (centerx, centery))
screen.blit(screen_text, rect)
Pass the center of the rectangle to the drawTextCenter function:
button_1 = pygame.Rect(50, 100, 200, 50)
drawTextCenter('main menu', button_1.centerx, button_1.centery, 20)
Do not create the pygame.font.Font object in every frame. Create the font once at the begin of the program. Creating a font object is very time consuming because the font file has to be read and interpreted.
I was making a code where on clicking a button, a string will be chosen randomly from myList and be displayed. I am doing this using pygame module. The problem here is that the text does not remain, it just flashes for one frame.
Here's the code:
import pygame
import random
pygame.init()
size = (500, 400)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Project")
bg = pygame.image.load("bg.jpg")
# declaring variables and lists
white = (255, 255, 255)
black = (0, 0, 0)
light_grey = (224, 224, 224)
dark_grey = (200, 200, 200)
text = pygame.font.SysFont("Agency FB", 20)
myList = ["China", "Italy", "Russia", "India", "USA", "Canada", "France", "Japan", "Brazil", "Egypt"]
# text for button
button_text = text.render("Country", True, black)
rb = random.choice(myList)
font = pygame.font.SysFont("Agency FB", 50)
bFont = font.render(str(rb), True, white)
var = True
while var:
screen.blit(bg, (0, 0))
# store mouse position
mouse = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
var = False
# button click
if event.type == pygame.MOUSEBUTTONDOWN:
# pick one from list and blit
if 50 <= mouse[0] <= 50 + 75 and 350 <= mouse[1] <= 350 + 35:
screen.blit(bFont, (50, 100))
# make button
if 50 <= mouse[0] <= 50 + 75 and 350 <= mouse[1] <= 350 + 35:
pygame.draw.rect(screen, dark_grey, (50, 350, 75, 35), 0)
else:
pygame.draw.rect(screen, light_grey, (50, 350, 75, 35), 0)
screen.blit(button_text, (55, 355))
pygame.display.update()
How can I get the text to be there and not vanish in the next frame?
Do not create bFont before the main application loop, but initialize it with None:
bFont = None
Choose and render a random string when the button is pressed:
while var:
# [...]
for event in pygame.event.get():
# [...]
# button click
if event.type == pygame.MOUSEBUTTONDOWN:
# pick one from list and blit
button_rect = pygame.Rect(50, 350, 75, 35)
if button_rect.collidepoint(event.pos):
rb = random.choice(myList)
bFont = font.render(str(rb), True, white)
Draw the text in the main application loop if bFont is set:
var = True
while var:
# [...]
if bFont:
screen.blit(bFont, (50, 100))
pygame.display.update()
Complete example:
import pygame
import random
pygame.init()
size = (500, 400)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Project")
bg = pygame.image.load("bg.jpg")
# declaring variables and lists
white = (255, 255, 255)
black = (0, 0, 0)
light_grey = (224, 224, 224)
dark_grey = (200, 200, 200)
text = pygame.font.SysFont("Agency FB", 20)
myList = ["China", "Italy", "Russia", "India", "USA", "Canada", "France", "Japan", "Brazil", "Egypt"]
# text for button
button_text = text.render("Country", True, black)
button_rect = pygame.Rect(50, 350, 75, 35)
font = pygame.font.SysFont("Agency FB", 50)
bFont = None
var = True
while var:
# store mouse position
mouse = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
var = False
# button click
if event.type == pygame.MOUSEBUTTONDOWN:
# pick one from list and blit
if button_rect.collidepoint(event.pos):
rb = random.choice(myList)
bFont = font.render(str(rb), True, white)
screen.blit(bg, (0, 0))
# make button
if button_rect.collidepoint(mouse):
pygame.draw.rect(screen, dark_grey, (50, 350, 75, 35), 0)
else:
pygame.draw.rect(screen, light_grey, (50, 350, 75, 35), 0)
screen.blit(button_text, (55, 355))
if bFont:
screen.blit(bFont, (50, 100))
pygame.display.update()
Try using another boolean var
if event.type == pygame.MOUSEBUTTONDOWN:
if 50 <= mouse[0] <= 50 + 75 and 350 <= mouse[1] <= 350 + 35:
show_text = True
if show_text:
time_check = pygame.time.get_ticks ()
b_font = font.render (random.choice (my_list), True,(255,255,255))
screen.blit (b_font, (50, 100)
if time_check >= 2000: #2000 miliseconds
show_text = False
time_check = 0
Here it will display your text for two seconds
I copied most of this code from an earlier script which worked fine, but when I load up the game, pretty much all the elements are flickering.
Here is the Minimal complete verifiable example here:
import pygame
pygame.init()
displayWidth = 1280
displayHeight = 720
gameDisplay = pygame.display.set_mode((displayWidth, displayHeight))
pygame.display.set_caption('Grow')
black = (0, 0, 0)
brown = (100, 100, 0)
green = (0, 200, 0)
lightGreen = (0, 255, 0)
red = (200, 0, 0)
lightRed = (255, 0, 0)
smallfont = pygame.font.SysFont("comicsansms", 25)
medfont = pygame.font.SysFont("comicsansms", 50)
largefont = pygame.font.SysFont("comicsansms", 80)
clock = pygame.time.Clock()
FPS = 60
def gameIntro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(brown)
message_to_screen('Welcome to Tanks', green, -100, 'large')
message_to_screen('The objective is to shoot and destroy', black, -30)
message_to_screen('Shoot and destroy the enemy tank before they destroy you', black, 10)
message_to_screen('The more enemies you destroy, the harder they get', black, 50)
button('quit', 500, 500, 100, 50, red, lightRed, action = 'quit')
button('play', 200, 500, 100, 50, green, lightGreen, action = 'play')
pygame.display.update()
clock.tick(0)
def gameLoop():
pygame.quit()
quit()
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(gameDisplay, active_color, (x, y, width, height))
if click[0] == 1 and action != None:
if action == 'quit':
pygame.quit()
quit()
if action == 'play':
gameLoop()
else:
pygame.draw.rect(gameDisplay, inactive_color, (x, y, width, height))
text_to_button(text, black, x, y, width, height)
def text_to_button(msg, colour, buttonx, buttony, buttonwidth, buttonheight, size = 'small'):
textSurf, textRect = text_objects (msg, colour, size)
textRect.center = ((buttonx + (buttonwidth/2)), buttony + (buttonheight/2))
gameDisplay.blit(textSurf, textRect)
pygame.display.update()
def message_to_screen(msg, colour, y_displace = 0, size = 'small'):
textSurf, textRect = text_objects (msg, colour, size)
textRect.center = (displayWidth / 2), (displayHeight / 2) + y_displace
gameDisplay.blit(textSurf, textRect)
pygame.display.update()
def text_objects(text, colour, size):
if size == 'small':
textSurface = smallfont.render (text, True, colour)
elif size == 'medium':
textSurface = medfont.render (text, True, colour)
elif size == 'large':
textSurface = largefont.render (text, True, colour)
return textSurface, textSurface.get_rect()
gameIntro()
For some reason, in the gameIntro function, when I call the message_to_screen and button functions, they all start flickering (everything except the first function called). Changing the order of the functions changes which one will stop flickering. Everything else works fine. The buttons change colour when the cursor is above them and they can still be clicked and have functionality
Don't call pygame.display.update() multiple times in each iteration of your game loop. It will lead to the screen flickering you see.
Simply remove the pygame.display.update() calls in the message_to_screen and text_to_button functions.
I thought I would give pygame a try and have ran into an issue that I hope someone can help me with. I would like to have a class def to create the quit button but when I do this I can't get the mouse collision. I am most likely doing it wrong, but would really appreciate the help.
It works in the state I have below but not when I put it in a def!
pygame.init()
class Window:
def __init__(self):
self.screen_width = 800
self.screen_height = 600
self.screen = (pygame.display.set_mode((self.screen_width, self.screen_height)))
self.FPS = 30
self.clock = pygame.time.Clock()
self.font = pygame.font.SysFont('Arial', 25)
self.menu_open = True
self.colors = {"red": (255, 0, 0),
"green": (0, 255, 0),
"blue": (0, 0, 255),
"white": (255, 255, 255),
"black": (0, 0, 0),
"brown": (153, 76, 0),
"grey": (100, 100, 100)}
def setup(self):
self.screen.fill(self.colors["black"])
pygame.display.set_caption("Menu Test!")
def text(self, message, text_color, x_pos, y_pos):
text = self.font.render(message, True, (self.colors[text_color]))
text_rect = text.get_rect(center=(x_pos, y_pos))
self.screen.blit(text, text_rect)
def exit(self):
self.screen.fill(self.colors["black"])
text = self.font.render("Thank you for playing. Goodbye!", True,
(self.colors["white"]))
text_rect = text.get_rect(center=(self.screen_width / 2,
self.screen_height / 2))
self.screen.blit(text, text_rect)
pygame.display.update()
sleep(3)
pygame.quit()
sys.exit()
def main():
window = Window()
window.setup()
This is the bit i would like in a class def
quit_button = pygame.draw.rect(window.screen, window.colors["white"],
(window.screen_width / 2 - 100,
window.screen_height / 1.5 - 25, 200, 50), 0)
window.text("QUIT", "red", window.screen_width / 2, window.screen_height / 1.5)
pygame.display.update()
while window.menu_open == 1:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
And this is where it get the posistion of the mouse click on the rect.
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
pos = pygame.mouse.get_pos()
if quit_button.collidepoint(pos):
window.exit()
else:
print("Error Line 48")
if __name__ == "__main__":
main()
Create a class (in this case I use a pygame.sprite.Sprite subclass) with an image and a rect attribute and blit the text onto the image.
import sys
import pygame as pg
pg.init()
class Window:
def __init__(self):
self.screen = pg.display.set_mode((800, 600))
self.rect = self.screen.get_rect()
self.FPS = 30
self.clock = pg.time.Clock()
self.font = pg.font.SysFont("Arial", 25)
self.menu_open = True
self.colors = {"red": (255, 0, 0),
"green": (0, 255, 0),
"blue": (0, 0, 255),
"white": (255, 255, 255),
"black": (0, 0, 0),
"brown": (153, 76, 0),
"grey": (100, 100, 100)}
def setup(self):
self.screen.fill(self.colors["black"])
pg.display.set_caption("Menu Test!")
def text(self, message, text_color, x_pos, y_pos):
text = self.font.render(message, True, (self.colors[text_color]))
text_rect = text.get_rect(center=(x_pos, y_pos))
self.screen.blit(text, text_rect)
def exit(self):
self.screen.fill(self.colors["black"])
text = self.font.render("Thank you for playing. Goodbye!", True,
(self.colors["white"]))
text_rect = text.get_rect(center=(self.rect.w/2, self.rect.h/2))
self.screen.blit(text, text_rect)
pg.display.update()
pg.time.wait(1000)
pg.quit()
sys.exit()
class Button(pg.sprite.Sprite):
def __init__(self, pos, text, window):
super().__init__() # Call __init__ of the parent class.
# Render the text.
self.text_surf = window.font.render(text, True, window.colors["black"])
self.image = pg.Surface((self.text_surf.get_width()+40,
self.text_surf.get_height()+20))
self.image.fill(window.colors["white"])
# Now blit the text onto the self.image.
self.image.blit(self.text_surf, (20, 10))
self.rect = self.image.get_rect(topleft=pos)
def main():
window = Window()
window.setup()
clock = pg.time.Clock()
# gui is a sprite group which will contain the button sprites.
gui = pg.sprite.Group()
# Instantiate some buttons.
quit_button = Button(
pos=(window.rect.w/2 - 100, window.rect.h/1.5 - 25),
text="QUIT",
window=window,
)
hello_button = Button(
pos=(window.rect.w/8, window.rect.h/2),
text="hello",
window=window,
)
# Add the buttons to the gui group.
gui.add(quit_button, hello_button)
while window.menu_open == True:
for event in pg.event.get():
if event.type == pg.QUIT:
window.exit()
if event.type == pg.MOUSEBUTTONDOWN and event.button == 1:
# Handle button events.
if quit_button.rect.collidepoint(event.pos):
window.exit()
elif hello_button.rect.collidepoint(event.pos):
print("hello")
gui.update() # Call update methods of contained sprites.
gui.draw(window.screen) # Draw all sprites.
pg.display.flip()
clock.tick(30)
if __name__ == "__main__":
main()
A bit more advanced solution would be to handle the events in the Button class and then call a callback function which you have to pass during the instantiation.
class Button(pg.sprite.Sprite):
def __init__(self, pos, text, window, callback):
super().__init__()
self.text_surf = window.font.render(text, True, window.colors["black"])
self.image = pg.Surface((self.text_surf.get_width()+40,
self.text_surf.get_height()+20))
self.image.fill(window.colors["white"])
self.image.blit(self.text_surf, (20, 10))
self.rect = self.image.get_rect(topleft=pos)
# The callback function will be called when
# the left mouse button gets pressed.
self.callback = callback
def handle_event(self, event):
if event.type == pg.MOUSEBUTTONDOWN and event.button == 1:
if self.rect.collidepoint(event.pos):
self.callback() # Call the callback function.
def main():
window = Window()
window.setup()
clock = pg.time.Clock()
gui = pg.sprite.Group()
quit_button = Button(
pos=(window.rect.w/2 - 100, window.rect.h/1.5 - 25),
text="QUIT",
window=window,
callback=window.exit, # Pass the callback function.
)
hello_button = Button(
pos=(window.rect.w/8, window.rect.h/2),
text="hello",
window=window,
callback=lambda: print("hello"), # Pass the callback function.
)
gui.add(quit_button, hello_button)
while window.menu_open == True:
for event in pg.event.get():
if event.type == pg.QUIT:
window.exit()
# Iterate over the gui group and pass the event to the buttons.
# If they collide with the mouse, call the callback func.
for button in gui:
button.handle_event(event)
gui.update()
gui.draw(window.screen)
pg.display.flip()
clock.tick(30)
if __name__ == "__main__":
main()