有没有办法将html嵌入到pygame中

per*_*ert 5 html python pygame python-3.x

所以,我试图在 中创建一个虚拟助手pygame,但我找不到任何将搜索结果添加到窗口中的方法,我打算使用 Web 抓取所有 html 并将beatifulsoup该 html 放入 中pygame,但问题是我不知道如何将 html 嵌入其中pygame,并且要明确的是,我不是在谈论嵌入pygame到 html,而是将 html 放入pygame窗口中

slo*_*oth 5

无法直接在 pygame 中执行此操作。但是您可以使用wkhtmltoimage这样的外部工具将 HTML 渲染为图像并在 pygame 中使用它。

这是一个使用imgkit(wkhtmltoimage 的 python 包装器)的简单示例:

import pygame
import imgkit
from io import BytesIO

def main():
    config = imgkit.config(wkhtmltoimage=r'C:\Program Files\wkhtmltopdf\bin\wkhtmltoimage.exe')

    pygame.init()
    screen = pygame.display.set_mode((600, 480))

    html = "<style type = 'text/css'> body { font-family: 'Arial' } </style><body><h1>Html rendering</h1><div><ul><li><em>using pygame</em></li><li><strong>using imgkit</strong></li></ul></div></body>"
    img = imgkit.from_string(html, False, config=config)
    surface = pygame.image.load(BytesIO(img)).subsurface((0,0,280,123))
    r = 0
    center = screen.get_rect().center
    clock = pygame.time.Clock()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT: 
                return

        screen.fill('white')
        tmp = pygame.transform.rotozoom(surface, r, 1)
        tmp_r = tmp.get_rect(center=center)
        screen.blit(tmp, tmp_r)
        r += 1
        pygame.display.flip()
        clock.tick(60)

if __name__ == '__main__':
    main()    
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述