How to display text in pygame
All functions draw in buffer and you have to send buffer to VideoCard which will display to screen.
You need pygame.display.flip()
or pygame.display.update()
for this.
pygame + opengl = display text
Use glWindowPos
instead of glRasterPos
. While the coordinates of glRasterPos
are transformed by the current modelview and projection matrices, glWindowPos
directly updates the x and y coordinates of the current raster position.
See also PyGame and OpenGL immediate mode (Legacy OpenGL) - Text
Minimal example:
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
verticies = ((1, -1, -1), (1, 1, -1), (-1, 1, -1), (-1, -1, -1),
(1, -1, 1), (1, 1, 1), (-1, -1, 1), (-1, 1, 1))
edges = ((0,1), (0,3), (0,4), (2,1),(2,3), (2,7), (6,3), (6,4),(6,7), (5,1), (5,4), (5,7))
def drawCube():
global edges
glBegin(GL_LINES)
for edge in edges:
for vertex in edge:
glVertex3fv(verticies[vertex])
glEnd()
def drawText(x, y, text):
textSurface = font.render(text, True, (255, 255, 66, 255), (0, 66, 0, 255))
textData = pygame.image.tostring(textSurface, "RGBA", True)
glWindowPos2d(x, y)
glDrawPixels(textSurface.get_width(), textSurface.get_height(), GL_RGBA, GL_UNSIGNED_BYTE, textData)
pygame.init()
clock = pygame.time.Clock()
display = (400, 300)
pygame.display.set_mode(display, DOUBLEBUF | OPENGL)
font = pygame.font.SysFont('arial', 64)
gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)
glTranslatef(0.0, 0.0, -5)
run = True
while run:
clock.tick(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
glRotatef(1, 3, 1, 1)
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
drawCube()
drawText(140, 120, "cube")
pygame.display.flip()
pygame.quit()
exit()
For text with a transparent background, you need to convert the text surface to a per pixel format using convert_alpha()
:
textSurface = font.render(text, True, (255, 255, 66, 255)).convert_alpha()
Additionally you have to enable Blending:
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
Minimal example:
replit.com/@Rabbid76/pygame-opengl-text
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
verticies = ((1, -1, -1), (1, 1, -1), (-1, 1, -1), (-1, -1, -1),
(1, -1, 1), (1, 1, 1), (-1, -1, 1), (-1, 1, 1))
edges = ((0,1), (0,3), (0,4), (2,1),(2,3), (2,7), (6,3), (6,4),(6,7), (5,1), (5,4), (5,7))
def drawCube():
global edges
glBegin(GL_LINES)
for edge in edges:
for vertex in edge:
glVertex3fv(verticies[vertex])
glEnd()
def drawText(x, y, text):
textSurface = font.render(text, True, (255, 255, 66, 255)).convert_alpha()
textData = pygame.image.tostring(textSurface, "RGBA", True)
glWindowPos2d(x, y)
glDrawPixels(textSurface.get_width(), textSurface.get_height(), GL_RGBA, GL_UNSIGNED_BYTE, textData)
pygame.init()
clock = pygame.time.Clock()
display = (400, 300)
pygame.display.set_mode(display, DOUBLEBUF | OPENGL)
font = pygame.font.SysFont('arial', 64)
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)
glTranslatef(0.0, 0.0, -5)
run = True
while run:
clock.tick(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
glRotatef(1, 3, 1, 1)
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
drawCube()
drawText(140, 120, "cube")
pygame.display.flip()
pygame.quit()
exit()
Make a Single Word Within a String Bold
No it is not possible. You must use the "bold" version of the font. "bold" isn't a flag or attribute, it's just a different font. So you need to render the word "Text" with one font and the word "Some" with another font.
You can use pygame.font.match_font()
to find the path to a specific font file.
Minimal example:
import pygame
pygame.init()
window = pygame.display.set_mode((400, 200))
clock = pygame.time.Clock()
courer_regular = pygame.font.match_font("Courier", bold = False)
courer_bold = pygame.font.match_font("Courier", bold = True)
font = pygame.font.Font(courer_regular, 50)
font_b = pygame.font.Font(courer_bold, 50)
text1 = font.render("Some ", True, (255, 255, 255))
text2 = font_b.render("Text", True, (255, 255, 255))
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.fill(0)
window.blit(text1, (50, 75))
window.blit(text2, (50 + text1.get_width(), 75))
pygame.display.flip()
clock.tick(60)
pygame.quit()
exit()
With the pygame.freetype
modle the text can be rendered with different styles like STYLE_DEFAULT
and STYLE_STRONG
. However, the text can only be rendered with one style at a time. So you still have to render each word separately:
import pygame
import pygame.freetype
pygame.init()
window = pygame.display.set_mode((400, 200))
clock = pygame.time.Clock()
ft_font = pygame.freetype.SysFont('Courier', 50)
text1, rect1 = ft_font.render("Some ",
fgcolor = (255, 255, 255), style = pygame.freetype.STYLE_DEFAULT)
text2, rect2 = ft_font.render("Text",
fgcolor = (255, 255, 255), style = pygame.freetype.STYLE_STRONG)
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.fill(0)
window.blit(text1, (50, 75))
window.blit(text2, (50 + rect1.width, 75))
pygame.display.flip()
clock.tick(60)
pygame.quit()
exit()
See also Text and font
Pygame pop up text
If you want to control something over time in Pygame you have two options:
Use
pygame.time.get_ticks()
to measure time and implement logic that controls the visibility of the text depending on the time.pygame.time.get_ticks()
returns the number of milliseconds sincepygame.init()
. Get the current time the text pops up and calculate the time the text must disappear:draw_text = true
hide_text_time = pygame.time.get_ticks() + 1000 # 1 secondif draw_text and pygame.time.get_ticks() > hide_text_time:
draw_text = falseUse the timer event. Use
pygame.time.set_timer()
to repeatedly create aUSEREVENT
in the event queue. The time has to be set in milliseconds. Start a timer event when the text pops up and hide the text when the event occurs:draw_text = true
hide_text_event = pygame.USEREVENT + 1
pygame.time.set_timer(hide_text_event, 1000, 1) # 1 second, one time# applicaition loop
while True:
# event loop
for event in pygame.event.get():
if event.type == hide_text_event:
draw_text = False
For some complete examples, see the answers to the questions:
- Adding a particle effect to my clicker game
- Spawning multiple instances of the same object concurrently in python.
Minimal example (the pop up time can be controlled with the variable pop_up_seconds
):
import pygame
pygame.init()
window = pygame.display.set_mode((400, 200))
font = pygame.font.SysFont(None, 40)
clock = pygame.time.Clock()
text = font.render("+1", True, (0, 255, 0))
text_pos_and_time = []
pop_up_seconds = 1
player = pygame.Rect(0, 80, 40, 40)
coins = [pygame.Rect(i*100+100, 80, 40, 40) for i in range(3)]
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
player.x = (player.x + (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * 3) % 300
current_time = pygame.time.get_ticks()
for coin in coins[:]:
if player.colliderect(coin):
text_pos_and_time.append((coin.center, current_time + pop_up_seconds * 1000))
coins.remove(coin)
window.fill(0)
pygame.draw.rect(window, "red", player)
for coin in coins:
pygame.draw.circle(window, "yellow", coin.center, 20)
for pos_time in text_pos_and_time[:]:
if pos_time[1] > current_time:
window.blit(text, text.get_rect(center = pos_time[0]))
else:
text_pos_and_time.remove(pos_time)
pygame.display.flip()
pygame.quit()
exit()
Writing text in pygame
http://www.daniweb.com/software-development/python/code/244474/pygame-text-python
Here's a link to an example... the code you're kinda looking for is this I think...
# pick a font you have and set its size
myfont = pg.font.SysFont("Comic Sans MS", 30)
# apply it to text on a label
label = myfont.render("Python and Pygame are Fun!", 1, yellow)
# put the label object on the screen at point x=100, y=100
screen.blit(label, (100, 100))
Related Topics
Convert Year/Month/Day to Day of Year in Python
Remove All Line Breaks from a Long String of Text
Running Bash Script from Within Python
Get Number of Items from List (Or Other Iterable) with Certain Condition
Selenium: Get Coordinates or Dimensions of Element with Python
How to Set Layer-Wise Learning Rate in Tensorflow
Requests: How to Disable/Bypass Proxy
Django Template Can't Loop Defaultdict
Double Precision Floating Values in Python
Safe Way to Parse User-Supplied Mathematical Formula in Python
Web Scraping Dynamic Content with Python
How to Split/Partition a Dataset into Training and Test Datasets For, E.G., Cross Validation