What's the easiest way to generate an error window for a Python script in Windows? Windows-specific answers are fine; please don't reply how to generate a custom Tk window.
Asked
Active
Viewed 2.2k times
9
-
What's wrong with Tk? It is very easy to create a message box with tkinter. – Gary Kerr Jul 29 '10 at 18:14
-
I was looking for a one-liner – Scribble Master Jul 29 '10 at 18:23
5 Answers
13
@Constantin is almost correct, but his example will produce garbage text. Make sure that the text is unicode. I.e.,
ctypes.windll.user32.MessageBoxW(0, u"Error", u"Error", 0)
...and it'll work fine.

Chris
- 1,421
- 3
- 18
- 31
-
Almost correct :) In 3.x `ctypes.windll.user32.MessageBoxW(0, "Error", "Error", 0)` would have worked as expected, and `u"Error"` would not compile at all. – Constantin Jul 29 '10 at 18:32
-
Ah, good to know. It's gonna be a major headache when I'm forced to move to py3k! – Chris Jul 29 '10 at 18:34
-
I'm using 2.5 for compatibility reasons, so Chris's is what I needed. Moving to 3.0 really is going to be very difficult! – Scribble Master Jul 29 '10 at 18:38
-
@Scribble Master, fortunately official 2to3 conversion tool removes much of that headache. – Constantin Jul 29 '10 at 20:52
-
You probably want `ctypes.windll.user32.MessageBoxW(0, u"Error", u"Error", 16)` -- this gives you the error icon + sound – GuiTaek Jul 17 '22 at 18:56
3
If you need a GUI error message, you could use EasyGui:
>>> import easygui as e
>>> e.msgbox("An error has occured! :(", "Error")
Otherwise a simple print("Error!")
should suffice.

John Howard
- 61,037
- 23
- 50
- 66
-
1That works, thanks! Not so great that I have to install another library, though. And it is based on Tkinter. I wanted something that would call the windows api directly. – Scribble Master Jul 29 '10 at 18:25
2
If i recall correctly (don't have Windows box at the moment), the ctypes
way is:
import ctypes
ctypes.windll.user32.MessageBoxW(None, u"Error", u"Error", 0)
ctypes is a standard module.
Note: For Python 3.x you don't need the u
prefix.

Constantin
- 27,478
- 10
- 60
- 79
2
You can get a one-liner using tkinter.
import tkMessageBox
tkMessageBox.showerror('error title', 'error message')
Here is some documentation for pop-up dialogs.

Gary Kerr
- 13,650
- 4
- 48
- 51
-
Ah, I didn't know that, thanks! I do prefer the direct win32 call, though – Scribble Master Jul 29 '10 at 18:40
-
1Note that with this answer you will also get a main window. See [this answer](http://stackoverflow.com/questions/17280637/tkinter-messagebox-without-window) for details. – Brown Apr 05 '17 at 14:11