Python 3 Tkinter - 如何在顶层窗口中弹出消息框?

8
我发现当一个顶层窗口调用消息框对话框(如 "showinfo"),根窗口会显示在顶层窗口之上。有没有办法将Toplevel窗口设置为消息框对话框的主窗口?
以下是重现此问题的脚本:
# -*- coding:utf-8 -*-
# PYTHON 3 ONLY

from tkinter import *
from tkinter import messagebox

root = Tk()
root.title('ROOT WINDOW')
Label(root, text = 'Place the toplevel window over the root window\nThen, push the button and you will see that the root window is again over the toplevel').grid()

topWindow = Toplevel(root)
topWindow.title('TOPLEVEL WINDOW')
Label(topWindow, text = 'This button will open a messagebox but will\ndo a "focus_force()" thing on the root window').grid()
Button(topWindow, text = '[Push me !]', command = lambda: messagebox.showinfo('foo', 'bar!')).grid()

# --

root.mainloop()
4个回答

16

3
这可能适用于更高版本。
#TEST AREA forcommands/methods/options/attributes
#standard set up header code 2 
from tkinter import *
from tkinter import messagebox
root = Tk()
root.attributes('-fullscreen', True)
root.configure(background='white')
scrW = root.winfo_screenwidth()
scrH = root.winfo_screenheight()  
workwindow = str(1024) + "x" + str(768)+ "+" +str(int((scrW-1024)/2)) + "+" +str(int((scrH-768)/2))
top1 = Toplevel(root, bg="light blue")
top1.geometry(workwindow)
top1.title("Top 1 - Workwindow")
top1.attributes("-topmost", 1)  # make sure top1 is on top to start
root.update()                   # but don't leave it locked in place
top1.attributes("-topmost", 0)  # in case you use lower or lift
#exit button - note: uses grid
b3=Button(root, text="Egress", command=root.destroy)
b3.grid(row=0,column=0,ipadx=10, ipady=10, pady=5, padx=5, sticky = W+N)
#____________________________
root.withdraw()
mb1=messagebox.askquestion(top1, "Pay attention: \nThis is the message?")
messagebox.showinfo("Say Hello", "Hello World")
root.deiconify()
top1.lift(aboveThis=None)
#____________________________
root.mainloop()

我认为这可能适用于更当前的版本。 - BigDaddy
请编辑您的帖子以包含您的评论。评论用于请求澄清和回答其他评论。它们是次要的公民,经常被删除。您的评论应该一开始就是您答案的一部分。如果您忘记包含它,您应该编辑您的帖子而不是将其发布为评论。 - robinCTS
糟糕,我本应该是一个注释,这可能适用于更近期的版本:坐标根、顶层和消息框——这是数个可能解决方案中的一种。 - BigDaddy
请重新阅读我的上一条评论。要编辑您的答案,请点击答案左下方的单词edit(在shareflag之间)。 - robinCTS

1
在定义Toplevel之后添加topWindow.attributes("-topmost", 1),这应该可以解决问题。

1
Button(..., command=lambda: messagebox.showinfo("The Title", "A piece of text", parent=topWindow))

这一定会奏效。消息框的语法是:
messagebox.Function_Name(title, message [, options]) 

设置parent参数是其中一个选项。

你能多提供一些关于为什么这个解决方案有效并解决了OP的问题的信息吗? - Matthew Barlowe
通过将showinfo命令的parent参数设置为topWindow,可以解决上述问题。这样做将使tkinter messagebox的主窗口设置为topWindow。因此,根窗口将不会显示在topWindow之上。 - Pro Chess

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接