首页 > 解决方案 > 实时更新python窗口

问题描述

我正在寻找一种在 python 中创建一个窗口的方法,我可以在其中控制每个单独的像素。还有我可以使用函数实时更新它们的地方。我的目标是创建一个 python 包。所以这个想法是:

import package

app = package.main()

app.init() # This would create the window
app.set_pixel(0, 0, (255, 0, 0)) # And this would set the pixel with x = 0 and y = 0 to red

我尝试过使用 PyGame 和 Tkinter,但它们都使用主循环,并且在循环启动后调用的所有函数都不会执行,除非应用程序关闭。

有没有办法做这样的事情,一切都可以实时更新?

标签: pythontkinterpygame

解决方案


无需更新主循环之外的任何内容,您应该在循环本身内运行您的函数 - 主循环意味着它正在实时运行。如果没有,屏幕将不会更新(这基本上是循环所做的主要事情 - 更新屏幕)。

您可以在 Pygame 中尝试以下操作:

import pygame as pg

pg.init()

WIDTH = 1300
HEIGHT = 900

screen = pg.display.set_mode((WIDTH, HEIGHT))

# mainloop
running = True
while running:
    # event processing
    for event in pg.event.get():
        if event.type == pg.QUIT:
            running = False
            break

    # drawing section
    screen.set_at((1, 1), (255, 0, 0))
    pg.display.flip()

pg.quit()

screen.set_at((x, y), (r, g, b))函数是将特定像素设置为特定颜色的函数。

编辑:您可以编写一个名为的模块,该模块display具有一个函数,该函数接收您要在主循环中运行的函数并运行它。它看起来像这样:

import display

def func(screen):
    screen.set_at((1, 1), (255, 0, 0))

display.start(func)

推荐阅读