6

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

Results Of Above Code

How can I make this blank window not appear?

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Ecko
  • 1,030
  • 9
  • 30
  • possible duplicate of [How do I get rid of Python Tkinter root window?](http://stackoverflow.com/questions/1406145/how-do-i-get-rid-of-python-tkinter-root-window) – TigerhawkT3 Jun 16 '15 at 20:01
  • How are you using this code with the remaining of your code?...is it part of a class?..or what? – Iron Fist Jun 16 '15 at 20:05
  • The example given was not in anything. You could say it was in `__main__`. The actual code was inside a function, that's all. – Ecko Jun 16 '15 at 20:09

2 Answers2

11
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

maccartm
  • 2,035
  • 14
  • 23
  • Your import statement might work fine for Python 3.x actually, never used Tkinter on anything higher than 2.5, so if I'm incorrect about the import statements than disregard! – maccartm Jun 16 '15 at 20:30
  • As long as your imports worked with my solution then all is well, my code just shows what I had to use. – maccartm Jun 16 '15 at 22:02
  • If I give `Tk().withdraw()`, after my callback method is executed, program doesn't end. Any idea why? – Nagabhushan S N Dec 15 '18 at 06:46
  • 1
    Isn't there a need to destroy Tk() after `showerror` is closed? If so, the solution by @NagabhushanSN seems more complete. – Sun Bear Sep 19 '19 at 16:44
6

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.

Nagabhushan S N
  • 6,407
  • 8
  • 44
  • 87