在不阻塞代码的情况下在循环中连续创建弹出窗口

Create popups continuously in a loop without blocking the code

我的程序流式传输数据,我想创建一个弹出窗口,在满足条件时显示一些文本。我试图创建一个简单的 tkinter window 和 ctypes window,但两者似乎都阻止了我的代码,阻止它继续,直到 window 关闭。如何在循环中创建简单的弹出 window 功能?

到目前为止我所拥有的是这种结构。

import tkinter as tk
for i in range(11):
    if i%5 == 0:  # Any condition
        popup = tk.Tk()
        label = ttk.Label(popup, text='hi', font=('Verdana', 12))
        label.pack(side='top', padx=10, pady=10)
        popup.mainloop()

import ctypes
for i in range(11):
    if i%5 == 0:  # Any condition
        popup = ctypes.windll.user32.MessageBoxW
        popup(None, 'hi', 'title', 0)

但是,在这两种情况下,循环都不会继续,直到我关闭弹出窗口。

不太熟悉 ctypes,但对于 tkinter,UI 将始终在 mainloop 期间阻塞您的主代码。

如果你只是实例化你的 Tk() 而不调用 mainloop 并使用 after 函数,你可以稍微绕过它:

import tkinter as tk
from tkinter.messagebox import showinfo

root = tk.Tk()
root.withdraw()

for i in range(10):
    if i in (5, 8):
        root.after(ms=1, func=lambda x=i: showinfo('Message!', f'Stopped at {x}'))

# ... do something here

root.after 将消息框排队等待 1 毫秒 (ms=1) 后显示。

更好的方法可能是在 ctypes 中创建一个无模式的 message/dialog 框,但如前所述,我不太熟悉,快速搜索也没有找到任何简单的解决方案。

案例 1 - Tkinter:

您正在使用 ,这与真正的 while 循环没有什么不同。您可以通过删除它来使它连续 运行。

import tkinter as tk
from tkinter import ttk

for i in range(11):
    if i%5 == 0:  # Any condition
        popup = tk.Tk()
        label = ttk.Label(popup, text='hi', font=('Verdana', 12))
        label.pack(side='top', padx=10, pady=10)

案例 2 - Ctypes:

要使其连续 运行,您将不得不使用 threading

import ctypes, threading

for i in range(11):
    if i%5 == 0:  # Any condition
        popup = ctypes.windll.user32.MessageBoxW
        threading.Thread(target = lambda :popup(None, 'hi', 'title', 0)).start()