import pygame import pygame.locals import random pygame.init() screen=pygame.display.set_mode((240,200)) pygame.display.set_caption('Large Letter') def newletter(let): global text global button_rect # clear screen screen.fill((255,255,255)) # add the letter font = pygame.font.Font(None,200) # (10,10,10) is the colour text = font.render(let, 1, (10,10,10)) screen.blit(text, letter_offset) # 'New' button font2 = pygame.font.Font(None,30) font2.set_underline(True) button_text = font2.render('New', 1, (10,10,10)) # margin is the distance of the text from the edge of the screen margin = 6 # put the button in the top left hand corner # and keep the return value (a Rect) in a global variable # so that we can detect mouse clicks on it button_rect = screen.blit(button_text, (margin, margin)) pygame.display.update() # we use letter_offset later to adjust the mouse coordinates letter_offset = (70, 10) newletter('m') oldpos = (0, 0) running = True while running: # get one event off the event queue # waiting until there is one event = pygame.event.wait() if event.type == pygame.locals.QUIT: running = False if event.type == pygame.locals.MOUSEMOTION: newpos = event.pos # is the left button down? if event.buttons[0]: # see if the mouse is over the letter # the letter background is the same colour as the letter # but with zero alpha, ie transparent # ".a" fetches the alpha (transparency) value # adjust the mouse coordinates to be relative # to the corner of the letter surface offpos = (newpos[0]-letter_offset[0], newpos[1]-letter_offset[1]) try: if text.get_at(offpos).a > 50: # on the text # https://www.pygame.org/docs/ref/color_list.html colour = 'yellow' else: # on the background colour = 'blue' except IndexError: # off the edge of the letter's surface (variable 'text') colour = 'cornflowerblue' # draw a line from oldpos to newpos # the last parameter is the line width pygame.draw.line(screen, pygame.Color(colour), oldpos, newpos, 3) # remember the previous mouse position even if the button is up oldpos = newpos pygame.display.update() if event.type == pygame.locals.MOUSEBUTTONDOWN: if button_rect.collidepoint(event.pos): # clicking the button clears the screen # and generates a new letter newletter(chr(random.randint(ord('a'), ord('z')))) # ignore all other events