Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Pygame:打断文本行以适应屏幕_Python_Python 3.x_Pygame - Fatal编程技术网

Python Pygame:打断文本行以适应屏幕

Python Pygame:打断文本行以适应屏幕,python,python-3.x,pygame,Python,Python 3.x,Pygame,因此,我正在开发一个客户机-服务器应用程序,在该应用程序中,客户机向服务器请求一些信息,收到这些信息后,客户机会在Pygame屏幕上显示这些信息。问题是,我从服务器获得的信息是以列表的形式出现的(因为我使用pickle库发送它),并且我很难将此列表分成单独的行以适应屏幕 例如,这是来自服务器端的代码,用于发送有关服务器cpu使用率、内存等的信息: def mostra_uso_cpu_e_ram(socket_cliente): info1 =('Usuario solicitou In

因此,我正在开发一个客户机-服务器应用程序,在该应用程序中,客户机向服务器请求一些信息,收到这些信息后,客户机会在Pygame屏幕上显示这些信息。问题是,我从服务器获得的信息是以列表的形式出现的(因为我使用pickle库发送它),并且我很难将此列表分成单独的行以适应屏幕

例如,这是来自服务器端的代码,用于发送有关服务器cpu使用率、内存等的信息:

def mostra_uso_cpu_e_ram(socket_cliente):
    info1 =('Usuario solicitou Informações de uso de processamento e Memória')
    resposta = []
    cpu = ('Porcentagem: ',psutil.cpu_percent())
    resposta.append(cpu)
    processador = ('Nome e modelo do processador: ',cpuinfo.get_cpu_info()['brand'])
    resposta.append(processador)
    arquitetura = ('Arquitetura: ',cpuinfo.get_cpu_info()['arch'])
    resposta.append(arquitetura)
    palavra = ('Palavra do processador:', cpuinfo.get_cpu_info()['bits'])
    resposta.append(palavra)
    ftotal = ('Frequência total do processador:', cpuinfo.get_cpu_info()['hz_actual'])
    resposta.append(ftotal)
    fuso = ('Frequência de uso:', psutil.cpu_freq()[0])
    resposta.append(fuso)
    disk = ('Porcentagem de uso do disco:', psutil.disk_usage('/')[3])
    resposta.append(disk)
    mem = psutil.virtual_memory()
    mem_percent = mem.used/mem.total
    memoria = ('Porcentagem de memória usada:', mem_percent)
    resposta.append(memoria)
    bytes_resp = pickle.dumps(resposta)
    socket_cliente.send(bytes_resp)
    print(info1)
这是客户端:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(), 9999))

bytes_resp = s.recv(1024)
lista = pickle.loads(bytes_resp)

# Pygame screen and surface settings 
largura_tela = 800
altura_tela = 600
tela = pygame.display.set_mode((largura_tela, altura_tela))
background = pygame.Surface(tela.get_size())
tela.blit(background, (0,0))

#function used to break lines but shows nothing
#indentation seems a little lot to the right because it's inside another block of text

       def drawText(surface, text, rect, color, font, aa=False, bkg=None):
            rect = pygame.Rect(rect)
            text = str(lista)
            y = rect.top
            lineSpacing = -2

            fontHeight = font.size("Tg")[1]

            while text:
                i = 1

                if y + fontHeight > rect.bottom:
                    break

                # determine maximum width of line
                while font.size(text[:i])[0] < rect.width and i < len(text):
                    i += 1

                # if we've wrapped the text, then adjust the wrap to the last word      
                if i < len(text): 
                    i = text.rfind(" ", 0, i) + 1

                # render the line and blit it to the surface
                if bkg:
                    image = font.render(text[:i], 1, color, bkg)
                    image.set_colorkey(bkg)
                else:
                    image = font.render(text[:i], aa, color)

                surface.blit(image, (rect.left, y))
                y += fontHeight + lineSpacing

                text = text[i:]

            return text
        
        drawText(background, str(lista), (30,400,1300,350), verde, font, aa=True, bkg=None)


我的问题是:如何将这些列表分成几行,或者至少让它们符合pygame的表面边界?从pygame网站获得了此功能,但我不确定我的错误在哪里?

以下是如何将列表转换为文本行列表:

lst = [('Porcentagem: ', 15.2), ('Nome e modelo do processador: ', 'Intel(R) Core(TM) i5-4288U CPU @ 2.60GHz'), ('Arquitetura: ', 'X86_64'), ('Palavra do processador:', 64), ('Frequência total do processador:', '2.6000 GHz'), ('Frequência de uso:', 2600), ('Porcentagem de uso do disco:', 11.1), ('Porcentagem de memória usada:', 0.48642539978027344)]


lines = [''.join(map(str, items)) for items in lst]
print(lines)
输出:

['Porcentagem:15.2','Nome e modelo do Processor:Intel(R)Core(TM)i5-4288U CPU@2.60GHz','Arquitetura:X86_64','Palavra do Processor:64','Frequeuência total do Processor:2.6000 GHz','Frequeuência de uso:2600','Porcentagem de uso do disco:11.1','Porcentagem de mem Orria usada:0.48642539978027344']

我不能轻易地测试它,因为你还没有提供测试。一个潜在的问题可能是,
drawText()
函数看起来好像假定字体中的字符宽度都相同,但这并非适用于所有字体。

我建议您使用希望通过
drawText()
函数处理的列表示例替换服务器端代码。另外,请清楚地解释该函数如何没有按您希望的方式工作。在pygame网站上链接到该功能的源代码也会很有用。谢谢!我将要呈现的列表添加到帖子的底部。另外,我从这个站点获得了函数:。它不工作,因为它没有显示任何类型的错误,也没有结果,我不知道我错了什么
lst = [('Porcentagem: ', 15.2), ('Nome e modelo do processador: ', 'Intel(R) Core(TM) i5-4288U CPU @ 2.60GHz'), ('Arquitetura: ', 'X86_64'), ('Palavra do processador:', 64), ('Frequência total do processador:', '2.6000 GHz'), ('Frequência de uso:', 2600), ('Porcentagem de uso do disco:', 11.1), ('Porcentagem de memória usada:', 0.48642539978027344)]


lines = [''.join(map(str, items)) for items in lst]
print(lines)