You can paint text and draw coloured rectangles, and detect if mouse clicks are inside the coloured rectangle Key-presses are received from events. So you first receive a key event, extract the key, and then check if it is the 'q' key.
EDIT: Added an example, it is Python2, so if you're using Python3, some minor things have to change.
#!/usr/bin/env python2
import pygame
pygame.init()
pygame.font.init()
BLACK = (0, 0, 0)
DARK = (120, 120, 120)
LATE = (170, 170, 170)
NOTICE = (255, 0, 255)
NORMAL = (150, 150, 150)
WHITE = (200, 200, 200)
SHINY = (255, 255, 255)
RED = (200, 10, 10)
NORMAL_SMALL = (200, 200, 120)
NORMAL_MEDIUM = (180, 180, 120)
NORMAL_LARGE = (160, 160, 120)
DISPLAY_WIDTH = 200
DISPLAY_HEIGHT = 200
class Button(object):
def __init__(self, x, y, w, h, text, colour=None):
if colour is None:
colour = NORMAL
self.normal_colour = colour
self.x = x
self.y = y
self.w = w
self.h = h
self.font = pygame.font.Font(None, 20)
self.text = text
self.shiny = False
def draw(self, screen):
if self.shiny:
bg = SHINY
else:
bg = self.normal_colour
surf = self.font.render(self.text, True, BLACK, bg)
rect = (self.x, self.y, self.w, self.h)
xo = self.x + (self.w - surf.get_width()) // 2
yo = self.y + (self.h - surf.get_height()) // 2
screen.fill(bg, rect)
screen.blit(surf, (xo, yo))
def on_button(self, pos):
return self.x <= pos[0] and self.x + self.w > pos[0] and \
self.y <= pos[1] and self.y + self.h > pos[1]
def set_shiny(self, new_shiny):
self.shiny = new_shiny
def draw(screen):
screen.fill(BLACK)
for b in buttons:
b.draw(screen)
def update_click(pos):
for b in buttons:
if b.on_button(pos):
b.set_shiny(not b.shiny)
buttons = []
buttons.append(Button(10, 10, 150, 20, "myname", colour=RED))
buttons.append(Button(10, 100, 150, 30, "yourname", colour=NORMAL))
screen = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
pygame.display.set_caption('Click Buttons')
done = False
while not done:
draw(screen)
pygame.display.flip()
# Wait until the next event.
event = pygame.event.wait()
# Release of the LMB.
if event.type == pygame.MOUSEBUTTONUP:
if event.button == 1 and update_click(event.pos):
pass # Update screen
# Window got closed.
elif event.type == pygame.QUIT:
done = True
break
# Pressed 'q'.
elif event.type == pygame.KEYDOWN:
if event.key == ord('q'):
done = True
break