tkinter showerror creating blank tk window

雨燕双飞 提交于 2019-12-01 03:30:22

问题


I have a program that needs to display graphical error messages to users. It is a tkinter GUI, so I am using tkinter.messagebox.showerror

When I call showerror, it shows the error, but also creates a blank "tk" window, the kind created when an instance of the Tk class is called, like root = Tk().

from tkinter.messagebox import showerror
showerror(title = "Error", message = "Something bad happened")

Produces

How can I make this blank window not appear?


回答1:


from Tkinter import *
from tkMessageBox import showerror
Tk().withdraw()
showerror(title = "Error", message = "Something bad happened")

Calling Tk().withdraw() before showing the error message will hide the root window.

Note: from tkinter import * for Python 3.x




回答2:


As explained in this answer, Tkinter requires a root window before we create any more widgets/dialogs. If there is no root window, tkinter creates one. So, to make the blank window disappear, first we need to create a root window ourselves, hide it and destroy it once your dialog action is complete. Sample code below

from tkinter import Tk
from tkinter.messagebox import showerror

root = Tk()
root.withdraw()
showerror(title = "Error", message = "Something bad happened")
root.destroy()

Note: This is applicable when you just have to display a dialog and no other window exists.



来源:https://stackoverflow.com/questions/30877010/tkinter-showerror-creating-blank-tk-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!