我需要我的程序生成多个消息框。 它们必须立即级联生成。 (将其视为恶意事件的模仿)
我尝试使用 Tkinter 执行此操作:
import Tkinter
import tkMessageBox
for i in range(0,5):
tkMessageBox.showerror("", "oops")
但似乎程序在显示下一条之前等待用户与每条消息的交互,这并不是我所需要的 可选的,左上角有一个空表格。有什么办法摆脱它吗?
请您参考如下方法:
解决方案可能是在此处使用 TopLevel()。这将允许弹出所有窗口,您还可以设置客户消息框样式。
这是一个简单的例子,它会同时打开所有窗口,同时隐藏根窗口。下面将把所有的窗口堆叠在一起,你可以移动它们。如果愿意,您还可以提供一些跟踪变量以在不同位置打开每个窗口。
#For python 3 imports:
import tkinter as tk
from tkinter import ttk
# for python 2 imports:
# import Tkinter as tk
# import ttk
root = tk.Tk()
root.withdraw()
for i in range(0,5):
x = tk.Toplevel(root)
x.title("Error Box!")
x.geometry("150x75+0+0")
x.resizable(False, False)
ttk.Label(x, text = "oops").pack()
ttk.Button(x, text = " OK ", command = x.destroy).pack(side=tk.BOTTOM)
root.mainloop()
为了回应您对使用计数器的评论,请参阅以下代码:
#For python 3 imports:
import tkinter as tk
from tkinter import ttk
# for python 2 imports:
# import Tkinter as tk
# import ttk
root = tk.Tk()
root.withdraw()
counter = 0
def close_window(top_window):
global counter
top_window.destroy()
counter -= 1
if counter == 0:
print("destroying root window")
root.destroy()
for i in range(0,5):
counter += 1
x = tk.Toplevel(root)
x.title("Error Box!")
x.geometry("150x75+0+0")
x.resizable(False, False)
ttk.Label(x, text="oops").pack()
ttk.Button(x, text=" OK ", command=lambda tw=x: close_window(tw)).pack(side=tk.BOTTOM)
# this protocol() method is used to re-rout the window close event to a customer function.
# this will allow us to keep our counter and close windows as needed.
x.protocol("WM_DELETE_WINDOW", lambda tw=x: close_window(tw))
root.mainloop()
更好的是这里有一个将项目放在列表中的示例,因此我们不需要计数器。
#For python 3 imports:
import tkinter as tk
from tkinter import ttk
# for python 2 imports:
# import Tkinter as tk
# import ttk
root = tk.Tk()
root.withdraw()
list_of_windows = []
def close_window(tw):
i = list_of_windows.index(tw)
list_of_windows[i].destroy()
del list_of_windows[i]
if len(list_of_windows) == 0:
root.destroy()
print("root destroyed!")
for i in range(0,5):
x = tk.Toplevel(root)
x.title("Error Box!")
x.geometry("150x75+0+0")
x.resizable(False, False)
ttk.Label(x, text="oops").pack()
ttk.Button(x, text=" OK ", command=lambda tw=x: close_window(tw)).pack(side=tk.BOTTOM)
x.protocol("WM_DELETE_WINDOW", lambda tw=x: close_window(tw))
list_of_windows.append(x)
root.mainloop()
