9

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.

Scribble Master
  • 1,100
  • 3
  • 11
  • 17

5 Answers5

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
  • 1
    That 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
  • 1
    Note 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
1

Check out the GUI section of the Python Wiki for info on message boxs

asd32
  • 191
  • 1
  • 1
  • 6