Search code examples
pythonlinuxubuntucross-platform

How can I use an alert dialog with Python in linux?


My question is similar to this question, but I'm using Xubuntu, so the win32 api is obviously not available. Is there some alternative I can use?

I just need to have a simple window pop up with a message, from a python script.


Solution

  • You can do this with Tkinter, which is cross-platform, and commonly bundled with the standard Python package.

    import Tkinter as tk
    import tkMessageBox
    root = tk.Tk()
    root.withdraw()
    tkMessageBox.showwarning('alert title', 'Bad things happened!')
    

    (On Python 3, you need to change the first line to import tkinter as tk. And the import tkMessageBox line becomes from tkinter import messagebox, and a matching change is required for the last line).

    The next two lines create a root window for the application (which all Tkinter programs need), but then make that window invisible. And finally we display our alert.

    You may need to install python-tk (i.e. sudo apt-get install python-tk in Ubuntu distributions) before using Tkinter - it's not installed by default on some distributions.