I am trying to create a main menu (starting page) for a 3 player connect 4 but I am unable to create one I want 5 buttons (3 player game, 2 player game, single player, options, Quit).
Can anyone help? If possible can anyone give me example code which I could adapt to my game.
I haven't created a main menu before.
I don't mid use of tkinter or pygame.
CodePudding user response:
A small example of a yellow button, that when clicked prints some text (more explanation in code comments):
import pygame
pygame.init()
screen = pygame.display.set_mode((500, 400))
clock = pygame.time.Clock()
# create the surface that will be the button
btn = pygame.Surface((300, 200))
btn.fill((255, 255, 0))
rect = btn.get_rect(center=(250, 200))
clicked = False
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
screen.fill((0, 0, 0))
# get mouse pos
mouse_pos = pygame.mouse.get_pos()
# get the state of left mouse button
left, *_ = pygame.mouse.get_pressed()
# check if mouse is in the button and if the mouse button has been clicked
# the flag `clicked` is for registering the click once when button is pressed
# otherwise it will loop again and the conditions will be true again
# you can also use the event loop above to detect whether the
# mouse button has been pressed, then the flag is not needed
if rect.collidepoint(mouse_pos) and left and not clicked:
clicked = True
print('clicked')
# reset flag
if not left:
clicked = False
# show the button
screen.blit(btn, rect)
pygame.display.update()
Useful:
CodePudding user response:
Here’s a small example using Tkinter:
from tkinter import *
def click():
# Make another window.
top = Toplevel()
# You can add more elements here.
# Creating the Main Window
root = Tk()
root.title(“Connect 4”) # You can replace the title with your own
btn = Button(root, text=“Place Your Text”, command=click).pack()
# You can add as many of these buttons
root.mainloop()