179

I'm looking for the same effect as alert() in JavaScript.

I wrote a simple web-based interpreter this afternoon using Twisted Web. You basically submit a block of Python code through a form, and the client comes and grabs it and executes it. I want to be able to make a simple popup message, without having to rewrite a whole bunch of boilerplate wxPython or Tkinter code every time (since the code gets submitted through a form and then disappears).

I've tried tkMessageBox:

import tkMessageBox
tkMessageBox.showinfo(title="Greetings", message="Hello, World!")

but this opens another window in the background with the Tkinter icon. I don't want this. I was looking for some simple wxPython code, but it always required setting up a class and entering an application loop, etc. Isn't there a simple, catch-free way of making a message box in Python?

18 Answers 18

385

You could use an import and single line code like this:

import ctypes  # An included library with Python install.   
ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 1)

Or define a function (Mbox) like so:

import ctypes  # An included library with Python install.
def Mbox(title, text, style):
    return ctypes.windll.user32.MessageBoxW(0, text, title, style)
Mbox('Your title', 'Your text', 1)

Note the styles are as follows:

##  Styles:
##  0 : OK
##  1 : OK | Cancel
##  2 : Abort | Retry | Ignore
##  3 : Yes | No | Cancel
##  4 : Yes | No
##  5 : Retry | Cancel 
##  6 : Cancel | Try Again | Continue

Have fun!

Note: edited to use MessageBoxW instead of MessageBoxA

Sign up to request clarification or add additional context in comments.

17 Comments

Exactly what I was looking for. The OP too from what it sounds like. Should be marked as the answer!
Meh. Perhaps I spoke too soon. I'm only getting a single character for both title and message. Weird...
Had to use MessageBoxW instead of MessageBoxA.
@CodeMonkey in python 3, use MessageBoxW instead of MessageBoxA
If you want to raise the messagebox above other windows, set its last parameter to 0x00001000
|
65

Have you looked at easygui?

import easygui

easygui.msgbox("This is a message!", title="simple gui")

3 Comments

this is not tkinter, it's not shipped by default, strange, who is interested with introducing such simple functionality to bring unnecessary dependencies?
Actually gekannt, easygui is a wrapper around tkinter. Yes, it's an extra dependency, but it's a single python file. Some developers may think the dependency is worth it for implementing a dead-simple GUI.
still, pip install Tkinter for my win32 Windows10, as well as pip install win32com & pip install ctypes, not finding matching distributions, but easygui is being installed OK -- Thank you
24

Also you can position the other window before withdrawing it so that you position your message

#!/usr/bin/env python

from Tkinter import *
import tkMessageBox

window = Tk()
window.wm_withdraw()

#message at x:200,y:200
window.geometry("1x1+200+200")#remember its .geometry("WidthxHeight(+or-)X(+or-)Y")
tkMessageBox.showerror(title="error",message="Error Message",parent=window)

#centre screen message
window.geometry("1x1+"+str(window.winfo_screenwidth()/2)+"+"+str(window.winfo_screenheight()/2))
tkMessageBox.showinfo(title="Greetings", message="Hello World!")

2 Comments

Is there any method, so that we don't need to pross the ok button in the tkMessageBox and it process automatically?
@varsha_holla That's not how message box's work. You might want to look into creating a standard window with a timer.
23

The code you presented is fine! You just need to explicitly create the "other window in the background" and hide it, with this code:

import Tkinter
window = Tkinter.Tk()
window.wm_withdraw()

Right before your messagebox.

1 Comment

I had to add "window.destroy()" to the end of this to get it to exit cleanly.
19

Use:

import ctypes
ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 1)

The last number (here 1) can be changed to change the window style (not only buttons!):

## Button styles:
# 0 : OK
# 1 : OK | Cancel
# 2 : Abort | Retry | Ignore
# 3 : Yes | No | Cancel
# 4 : Yes | No
# 5 : Retry | No
# 6 : Cancel | Try Again | Continue

## To also change icon, add these values to previous number
# 16 Stop-sign icon
# 32 Question-mark icon
# 48 Exclamation-point icon
# 64 Information-sign icon consisting of an 'i' in a circle

For example,

ctypes.windll.user32.MessageBoxW(0, "That's an error", "Warning!", 16)

will give this:

Enter image description here

1 Comment

But only on Windows? I suggest adding something about this to the answer (but *** *** *** *** *** *** *** *** *** *** without *** *** *** *** *** *** *** *** *** *** "Edit:", "Update:", or similar - the answer should appear as if it was written today).
16

The PyMsgBox module does exactly this. It has message box functions that follow the naming conventions of JavaScript: alert(), confirm(), prompt() and password() (which is prompt() but uses * when you type). These function calls block until the user clicks an OK/Cancel button. It's a cross-platform, pure Python module with no dependencies outside of tkinter.

Install with: pip install PyMsgBox

Sample usage:

import pymsgbox
pymsgbox.alert('This is an alert!', 'Title')
response = pymsgbox.prompt('What is your name?')

Full documentation at http://pymsgbox.readthedocs.org/en/latest/

4 Comments

strange. you write that it has no dependencies, but when I try to use it it prints AssertionError: Tkinter is required for pymsgbox
I should change that: pymsgbox has no dependencies outside of the standard library, which tkinter is part of. What version of Python and what OS are you on?
Sorry, I am noob in Python, I thought that all python libs are installed through pip, but in fact part of libs are installed the other way - using system package manager. So I installed python-tk using my package manager. I'm using Python 2.7 on Debian.
offtopic: but the message box created by PyMsgBox/Tk looks pretty ugly on my Debian
11

In Windows, you can use ctypes with user32 library:

from ctypes import c_int, WINFUNCTYPE, windll
from ctypes.wintypes import HWND, LPCSTR, UINT
prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT)
paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0)
MessageBox = prototype(("MessageBoxA", windll.user32), paramflags)

MessageBox()
MessageBox(text="Spam, spam, spam")
MessageBox(flags=2, text="foo bar")

Comments

11

On Mac, the Python standard library has a module called EasyDialogs. There is also a (ctypes-based) Windows version at EasyDialogs for Windows 46691.0.

If it matters to you: it uses native dialogs and doesn't depend on Tkinter like the already-mentioned easygui, but it might not have as much features.

Comments

5

You can use pyautogui or pymsgbox:

import pyautogui
pyautogui.alert("This is a message box",title="Hello World")

Using pymsgbox is the same as using pyautogui:

import pymsgbox
pymsgbox.alert("This is a message box",title="Hello World")

Comments

3

Also you can position the other window before withdrawing it so that you position your message

from tkinter import *
import tkinter.messagebox

window = Tk()
window.wm_withdraw()

# message at x:200,y:200
window.geometry("1x1+200+200")  # remember its.geometry("WidthxHeight(+or-)X(+or-)Y")
tkinter.messagebox.showerror(title="error", message="Error Message", parent=window)

# center screen message
window.geometry(f"1x1+{round(window.winfo_screenwidth() / 2)}+{round(window.winfo_screenheight() / 2)}")
tkinter.messagebox.showinfo(title="Greetings", message="Hello World!")

Please Note: This is Lewis Cowles' answer just Python 3ified, since tkinter has changed since python 2. If you want your code to be backwords compadible do something like this:

try:
    import tkinter
    import tkinter.messagebox
except ModuleNotFoundError:
    import Tkinter as tkinter
    import tkMessageBox as tkinter.messagebox

Comments

2

ctype module with threading

I was using the Tkinter message box, but it would crash my code. I didn't want to find out why, so I used the ctypes module instead.

For example:

import ctypes

ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 1)

I got that code from Arkelis.


I liked that it didn't crash the code, so I worked on it and added a threading so the code after would run.

Example for my code

import ctypes
import threading


def MessageboxThread(buttonstyle, title, text, icon):
    threading.Thread(
        target=lambda: ctypes.windll.user32.MessageBoxW(buttonstyle, text, title, icon)
    ).start()

messagebox(0, "Your title", "Your text", 1)

For button styles and icon numbers:

## Button styles:
# 0 : OK
# 1 : OK | Cancel
# 2 : Abort | Retry | Ignore
# 3 : Yes | No | Cancel
# 4 : Yes | No
# 5 : Retry | No
# 6 : Cancel | Try Again | Continue

## To also change icon, add these values to previous number
# 16 Stop-sign icon
# 32 Question-mark icon
# 48 Exclamation-point icon
# 64 Information-sign icon consisting of an 'i' in a circle

1 Comment

The threaded messagebox is sexy.
1

A recent message box version is the prompt_box module. It has two packages: alert and message. Message gives you greater control over the box, but takes longer to type up.

Example Alert code:

import prompt_box

prompt_box.alert('Hello') #This will output a dialog box with title Neutrino and the 
#text you inputted. The buttons will be Yes, No and Cancel

Example Message code:

import prompt_box

prompt_box.message('Hello', 'Neutrino', 'You pressed yes', 'You pressed no', 'You 
pressed cancel') #The first two are text and title, and the other three are what is 
#printed when you press a certain button

Comments

1

I had to add a message box to my existing program. Most of the answers are overly complicated in this instance. For Linux on Ubuntu 16.04 (Python 2.7.12) with future proofing for Ubuntu 20.04 here is my code:

Program top

from __future__ import print_function       # Must be first import

try:
    import tkinter as tk
    import tkinter.ttk as ttk
    import tkinter.font as font
    import tkinter.filedialog as filedialog
    import tkinter.messagebox as messagebox
    PYTHON_VER="3"
except ImportError: # Python 2
    import Tkinter as tk
    import ttk
    import tkFont as font
    import tkFileDialog as filedialog
    import tkMessageBox as messagebox
    PYTHON_VER="2"

Regardless of which Python version is being run, the code will always be messagebox. for future proofing or backwards compatibility. I only needed to insert two lines into my existing code above.

Message box using parent window geometry

''' At least one song must be selected '''
if self.play_song_count == 0:
    messagebox.showinfo(title="No Songs Selected", \
        message="You must select at least one song!", \
        parent=self.toplevel)
    return

I already had the code to return if song count was zero. So I only had to insert three lines in between existing code.

You can spare yourself complicated geometry code by using parent window reference instead:

parent=self.toplevel

Another advantage is if the parent window was moved after program startup your message box will still appear in the predictable place.

Comments

1

Use

from tkinter.messagebox import *
Message([master], title="[title]", message="[message]")

The master window has to be created before. This is for Python 3. This is not for wxPython, but for Tkinter.

1 Comment

See my comment about "import *" on Robert's answer.
1
import sys
from tkinter import *

def mhello():
    pass
    return

mGui = Tk()
ment = StringVar()

mGui.geometry('450x450+500+300')
mGui.title('My YouTube Tkinter')

mlabel = Label(mGui, text ='my label').pack()

mbutton = Button(mGui, text ='ok', command = mhello, fg = 'red', bg='blue').pack()

mEntry = entry().pack

2 Comments

Also, please, for the love of all the is PEP8 and pythonic, wean yourself off "import *". It's bad, m'kay?
'Star' import: import *
0

If you want a message box that will exit if not clicked in time:

import win32com.client

WshShell = win32com.client.DispatchEx("WScript.Shell")

# Working Example BtnCode = WshShell.Popup("Next update to run at ", 10, "Data Update", 4 + 32)

# discriptions BtnCode = WshShell.Popup(message, delay(sec), title, style)

2 Comments

Please explain your solution. Thanks in advance. It looks like Windows/Windows Script Host/VBScript. In a Python flavour? What is the deal? For starters, it supposedly only works on Windows? What was it tested on?
0

Check out my Python module QuickGUI: pip install quickgui (it requires wxPython, but it doesn't require any knowledge of wxPython)

It can create any number of inputs (ratio, checkbox, and inputbox) and auto arrange them on a single GUI.

Comments

-1

It is not the best, but here is my basic message box using only Tkinter.

# Python 3.4
from tkinter import messagebox as msg;
import tkinter as tk;

def MsgBox(title, text, style):
    box = [
        msg.showinfo,    msg.showwarning, msg.showerror,
        msg.askquestion, msg.askyesno,    msg.askokcancel, msg.askretrycancel,
];

tk.Tk().withdraw(); # Hide the main window

if style in range(7):
    return box[style](title, text);

if __name__ == '__main__':

Return = MsgBox( # Use it like this:
    'Basic Error Example',

    ''.join([
        'The basic error example a problem with test',                   '\n',
        'and is unable to continue. The application must close.',        '\n\n',
        'Error code Test',                                               '\n',
        'Would you like visit http://wwww.basic-error-exemple.com/ for', '\n',
        'help?',
    ]),

    2,
);

print(Return);

Output:

Style    | Type        |  Button        |    Return
------------------------------------------------------
0          Info           Ok                'ok'
1          Warning        Ok                'ok'
2          Error          Ok                'ok'
3          Question       Yes/No            'yes'/'no'
4          YesNo          Yes/No            True/False
5          OkCancel       Ok/Cancel         True/False
6          RetryCancal    Retry/Cancel      True/False

4 Comments

You import formatting is completely bonkers. Are you an old COBOL or FORTRAN programmer, by any chance? ;-)
It doesn't even compile (indentation near "if __name__ == '__main__':"). Where was this copied from? Was it stitched together from several sources/web sites without any testing whatsoever?
Is this a bogus answer?
Doesn't work...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.