python - 实时更新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,但它们都使用主循环,并且在循环启动后调用的所有函数都不会执行,除非应用程序关闭。
有没有办法做这样的事情,一切都可以实时更新?
解决方案
无需更新主循环之外的任何内容,您应该在循环本身内运行您的函数 - 主循环意味着它正在实时运行。如果没有,屏幕将不会更新(这基本上是循环所做的主要事情 - 更新屏幕)。
您可以在 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)
推荐阅读
- wpf - 如何根据 Datagrid Row Selection 检查复选框 CellTemplate?
- java - 对作为一类实例的字段使用 Mock
- android - 如何创建文件并在环境变量中设置并在 build.gradle 中获取文件中的数据?
- jquery - 单击时在较大的内部显示较小的图像
- php - 无法从 MySQL 中删除行
- php - 使用 htaccess 规则将 API 路径重定向到 Slim Routes
- powershell - 为什么我的 PowerShell 脚本不遵守步骤顺序?
- apache-kafka - 领导者更改后,Spring kafka 消费者不提交到 kafka 服务器
- django - Django 设计模型 - 当状态字段的数据发生变化时,其余模型状态随之变化
- javascript - 在 Express.JS 中呈现页面之前的异步请求