Skip to main content
 首页 » 编程设计

python之使用 Pygame 加载更新的图像

2024年11月24日6grandyang

我正在使用 pygame 制作一个基本的 Mandelbrot 缩放程序,每次用户放大时,它都会使用 pillow 生成图像。更新此图像时,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() 

有没有办法在不重置窗口的情况下加载更新的图像?

请您参考如下方法:

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()