简体   繁体   English

如何在pygame的不同矩形上显示不同的文字?

[英]How to display different text on different rectangles in pygame?

I have created a Pygame application where I have about 25 rectangles.我创建了一个 Pygame 应用程序,其中有大约 25 个矩形。 I want to display 25 different text values (which is a numerical value but typecasted in str - I mention this because I believe we need string in the first argument) at the center of the rectangle.我想在矩形的中心显示 25 个不同的文本值(这是一个数值,但在str中类型转换 - 我提到这一点是因为我相信我们需要在第一个参数中使用字符串)。 I have imported a csv file that contains data.我已经导入了一个包含数据的 csv 文件。

def draw_point(text, pos):
    font = pygame.font.SysFont(None, 20)
    img = font.render(text, True, (0,0,0))
    window.blit(img, pos)

def loop_func():
    count = 0
    while count < total_length:
        data = data_pass[count] # data_pass is an empty list
        pygame.draw.rect(window, (255,255,255), (20, 20, width, height)) 
        draw_point(data, (width // 2, height // 2))
    

According to the loop_func() function, the variable ' data ' should be updated with a new value in every loop, and it is updating because I checked with the print() function.根据loop_func() function,变量“数据”应该在每个循环中更新一个新值,并且它正在更新,因为我检查了print() function。 But when I pass the variable to the draw_point() function, it seems the function does not display the desired value.但是当我将变量传递给draw_point() function 时,似乎 function 没有显示所需的值。 This is my output:这是我的 output:

在此处输入图像描述

It is actually 25 different rectangles with an almost similar background color.它实际上是 25 个不同的矩形,具有几乎相似的背景颜色。 I followed everything from the Pygame tutorial, but I am getting a very ugly font, and among 25 rectangles, only 1 rectangle shows the text at its center.我遵循了 Pygame 教程中的所有内容,但我的字体非常难看,在 25 个矩形中,只有 1 个矩形在其中心显示文本。

How can I fix this?我怎样才能解决这个问题?

All of the text is drawn on top of each other.所有文本都绘制在彼此之上。 You need to draw the text at different positions.您需要在不同的位置绘制文本。 eg:例如:

def loop_func():
    count = 0
    while count < total_length:
        data = data_pass[count] # data_pass is an empty list
        pygame.draw.rect(window, (255,255,255), (20, 20, width, height)) 
        draw_point(data, (width // 2, height // 2 + count * 20))

If you want to draw the text at different times (counter), you need to change the text by time.如果要在不同时间(计数器)绘制文本,则需要按时间更改文本。 See for example How to display dynamically in Pygame?参见示例如何在 Pygame 中动态显示?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM