python - 我需要在矩形中添加文本,我该怎么做?
问题描述
我需要在按钮中绘制文本,在我的程序中可以将其视为四个较小的矩形,除此之外,我还需要在标题上绘制文本。我不确定如何做到这一点,因为我的程序结构与我见过的其他程序不同。
关注其他问题,以及他们收到的试图影响我的答案。
import pygame
import sys
def main():
pygame.init()
clock = pygame.time.Clock()
fps = 60
size = [700, 600]
bg = [255, 255, 255]
font = pygame.font.Font('freesansbold.ttf', 32)
screen = pygame.display.set_mode(size)
black = (0, 0, 0)
button = pygame.Rect(400, 400, 250, 125)
button2 = pygame.Rect(50, 400, 250, 125)
button3 = pygame.Rect(400, 250, 250, 125)
button4 = pygame.Rect(50, 250, 250, 125)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return False
if event.type == pygame.MOUSEBUTTONDOWN:
mouse_pos = event.pos # gets mouse position
# checks if mouse position is over the button
if button.collidepoint(mouse_pos):
# prints current location of mouse
print('Instructions'.format(mouse_pos))
if button2.collidepoint(mouse_pos):
# prints current location of mouse
print('Controls'.format(mouse_pos))
if button3.collidepoint(mouse_pos):
# prints current location of mouse
print('Information'.format(mouse_pos))
if button4.collidepoint(mouse_pos):
# prints current location of mouse
print('Start Game'.format(mouse_pos))
screen.fill(bg)
pygame.draw.rect(screen, black, (button)) # draw button
pygame.draw.rect(screen, black, (button2))
pygame.draw.rect(screen, black, (button3))
pygame.draw.rect(screen, black, (button4))
pygame.draw.rect(screen, black, (50, 25, 600, 200))
pygame.display.update()
clock.tick(fps)
pygame.quit()
sys.exit
if __name__ == '__main__':
main()
我希望按钮上有文字,所以将来当我点击它们时,它们会打开一个新窗口。
解决方案
如果您想使用pygame.font
,您必须通过以下方式呈现文本pygame.font.Font.render
:
例如
red = (255, 0, 0)
button = pygame.Rect(400, 400, 250, 125)
text = font.render("button 1", True, red)
结果是一个pygame.Surface
,它可以.blit
到矩形按钮区域的中心:
pygame.draw.rect(screen, black, button)
textRect = text.get_rect()
textRect.center = button.center
screen.blit(text, textRect)
另一种选择是使用pygame.freetype
:
例如
import pygame.freetype
ft_font = pygame.freetype.SysFont('Times New Roman', 32)
将文本直接渲染到屏幕上pygame.freetype.Font.render_to
text2 = "button 2"
textRect2 = ft_font.get_rect("button 2")
pygame.draw.rect(screen, black, button2)
textRect2.center = button2.center
ft_font.render_to(screen, textRect2, text2, red)
推荐阅读
- python - 单节点 Elasticsearch Docker SDK python
- javascript - 在 chart.js 中将 mysql x-axes 日期更改为当天
- debugging - Visual Studio 调试控制台显示额外信息,使阅读信息变得困难
- ruby-on-rails - 如何在 Procfile 和 app.json 中指定的 Heroku 上自动启用自定义工作人员测功机?
- docker - 在 Docker 容器上的 Apache 中运行 perl CGI 脚本
- python - TemplateResponseMixin 需要'template_name'的定义或'get_template_names()的实现 - Django 2.1
- python - 使用 Python 从纺织品中读取矩阵
- javascript - React Native 中的 FlatList 实现 - renderItem 功能不清楚?- 未定义的属性
- c# - 在 C# 中增加 IAsyncEnumerable 线程安全的整数吗?
- c# - SMTP 服务器需要安全连接或客户端未通过身份验证。请帮帮我