Reputation: 53
When I try to run this pygame code it instantly closes??
The window doesn't close instantly when I stop drawing text, so I know I must've done something wrong.
import pygame
background_colour = (255, 255, 255)
(width, height) = (1920, 1080)
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('fat')
screen.fill(background_colour)
font = pygame.font.Font(None, 32)
color = pygame.Color('dodgerblue2')
pygame.display.flip()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
text = ""
while running:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
vanishingtext += event.unicode
text += event.unicode
elif event.type == pygame.K_BACKSPACE:
text = text[:-1]
elif event.type == pygame.K_RETURN:
interpret(text)
text = ""
else:
pass
txt_surface = font.render(text, True, color)
screen.blit(txt_surface, (50, 100))
i expect for a screen to appear that allows me to type and backspace, if i press enter the text should completely disappear and a function should run that will interpret the string. i haven't defined interpet as a function yet, but i'm doing it after i've figured out if i can even make it work on a screen.
Upvotes: 2
Views: 308
Reputation: 14926
The code is not calling pygame.init()
. Also there's two event loops, the second of which will just drop straight-through once the running
becomes False
.
import pygame
pygame.init()
(width, height) = ( 400, 200)
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('fat')
background_colour = pygame.Color('white')
color = pygame.Color('dodgerblue2')
font = pygame.font.Font(None, 32)
clock = pygame.time.Clock()
running = True
text = ''
while running:
# handle events and user-input
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if ( event.key >= pygame.K_SPACE and event.key <= pygame.K_z ):
# Append key-stroke's character
text += event.unicode
elif ( event.key == pygame.K_BACKSPACE ):
text = text[:-1]
elif ( event.key == pygame.K_RETURN ):
print("interpret(text) - NOT IMPLEMENTED")
text = ""
# repaint the screen
screen.fill(background_colour)
txt_surface = font.render(text, True, color)
screen.blit(txt_surface, (50, 100))
pygame.display.flip()
clock.tick_busy_loop(60) # limit FPS
This code gives me a window titled "fat" with a white background. Typing on an english keyboard gives me blue letters, which can be backspaced. Pressing Enter is somewhat handled.
Upvotes: 1