首页 > 解决方案 > 使用 Pygame 加载更新的图像

问题描述

我正在使用 pygame 制作一个基本的 Mandelbrot 缩放程序,每次用户放大时使用枕头生成图像。更新此图像时,pygame 窗口仅加载原始图像而不是更新的图像。

我目前的解决方案是在每次缩放时杀死 pygame 窗口并重新初始化它,这会为每次缩放增加相当多的时间。这是我当前的代码

def pg_window(width, height):
    pg.init()

    fill_color = 255, 255, 255
    window = pg.display.set_mode((width, height))

    global set_image
    set_img = pg.image.load('mandelbrot.png')
    # The original load of the image
    zoom_x = int(width * .15)
    zoom_y = int(height * .15)

    while True:
        window.fill(fill_color)

        ... extra code ommitted ...

        for event in pg.event.get():
            if event.type == pg.QUIT:
                sys.exit()
            if event.type == pg.MOUSEBUTTONDOWN:
                zoom(*zoom_rect.center, width, height, zoom_x, zoom_y)
                # The zoom function call modifies the image directly.
                set_image = pg.image.load('mandelbrot.png')
                # changing the set_image variable just loads the original image, not the updated one
                # My current solution involves calling pg.quit() here
                # and recalling the pg_window function to reinitialize

        window.fill(fill_color)
        window.blit(set_img, (0, 0))
        pg.display.flip()

无论如何都可以在不重置窗口的情况下加载更新的图像?

标签: pythonpython-3.xpygamepython-imaging-library

解决方案


blit到窗口的图像的名称是set_img而不是set_image
所以你必须设置set_img

while True:
    window.fill(fill_color)

    # [...]

    for event in pg.event.get():

        # [...]

        if event.type == pg.MOUSEBUTTONDOWN:

            # [...]

            set_img = pg.image.load('mandelbrot.png') # <--- set_img 


        window.fill(fill_color)
        window.blit(set_img, (0, 0))
        pg.display.flip()

推荐阅读