我该如何在Python中创建一个简单的消息框?

171

我正在寻找与JavaScript中的alert()相同的效果。

今天下午,我使用Twisted Web编写了一个简单的基于Web的解释器。您可以通过表单提交一块Python代码,客户端会获取并执行它。我想能够制作一个简单的弹出消息,而不必每次都重写大量的样板wxPythonTkinter代码(因为代码通过表单提交然后消失)。

我尝试过tkMessageBox

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

但是这会在后台打开另一个带有Tkinter图标的窗口。我不想要这个。我正在寻找一些简单的wxPython代码,但它总是需要设置一个类并进入应用程序循环等等。难道没有一种简单、无风险的方法在Python中制作消息框吗?

18个回答

365

您可以使用导入并像这样编写单行代码:

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

或者定义一个名为(Mbox)的函数,如下所示:

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)

请注意以下样式:

##  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

玩得开心!

注意:已经编辑以使用MessageBoxW代替MessageBoxA


3
正是我要找的内容,从描述听起来OP也是。应该标记为答案! - CodeMonkey
3
可能我说话太快了。标题和消息只有一个字符。很奇怪... - CodeMonkey
21
不得不使用MessageBoxW而不是MessageBoxA。 - CodeMonkey
11
在Python 3中,使用MessageBoxW代替MessageBoxA。 - Oliver Ni
4
如果您想将消息框置于其他窗口之上,请将其最后一个参数设置为0x00001000。 - Lenny
显示剩余12条评论

62

你有没有看过 easygui

import easygui

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

10
这不是tkinter,它不会默认安装,很奇怪,有谁会对引入如此简单的功能以带来不必要的依赖感兴趣吗? - Tebe
11
实际上,Easygui是Tkinter的包装器。是的,这是一个额外的依赖,但它只是一个Python文件。一些开发人员可能认为这个依赖值得用来实现一个非常简单的GUI界面。 - Ryan Ginstrom

23

你提供的代码是正确的!你只需要明确创建“后台中的其他窗口”并隐藏它,使用以下代码:

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

就在你的消息框之前。


5
为了使程序干净退出,我不得不在末尾添加"window.destroy()"。 - kuzzooroo

22

你也可以在撤回另一个窗口之前将其定位,以便您定位消息。

#!/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!")

3
有没有一种方法,可以让我们不需要手动点击_tkMessageBox_中的_ok_按钮,而是自动处理它? - varsha_holla
@varsha_holla,消息框不是这样使用的。你可能想要考虑创建一个带有定时器的标准窗口。 - Kelly Elton

16

PyMsgBox模块正是做这件事的。它具有遵循JavaScript命名约定的消息框函数:alert(),confirm(),prompt()和password()(它使用*进行输入,但本质上与prompt()相同)。这些函数调用会阻塞,直到用户单击了一个OK/Cancel按钮。它是一个跨平台的纯Python模块,除了tkinter之外没有任何依赖。

安装方式:pip install PyMsgBox

示例用法:

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

完整文档请参阅http://pymsgbox.readthedocs.org/en/latest/


很奇怪,你写道它没有依赖项,但当我尝试使用它时,它会打印出“AssertionError:需要Tkinter来运行pymsgbox”。 - shitpoet
我应该更正一下:pymsgbox除了标准库外没有其他依赖项,其中包括tkinter。您使用的是哪个版本的Python和哪个操作系统? - Al Sweigart
抱歉,我在Python方面是个新手,我以为所有的Python库都是通过pip安装的,但实际上部分库是通过系统包管理器安装的。因此,我使用我的包管理器安装了python-tk。我在Debian上使用Python 2.7。 - shitpoet
离题一下:但是PyMsgBox/Tk创建的消息框在我的Debian上看起来非常丑。 - shitpoet

15

使用:

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

最后一个数字(这里是1)可以更改以更改窗口样式(不仅仅是按钮!):

## 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

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

将会给出this

Enter image description here


但是只在Windows上吗?我建议在答案中添加一些关于这个的内容(但是不要使用“编辑:”,“更新:”或类似的词语 - 答案应该看起来像今天写的)。 - Peter Mortensen

11

在Windows中,你可以使用ctypes和user32库

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")

10
在Mac上,Python标准库有一个名为EasyDialogs的模块。还有一个基于ctypes的Windows版本,位于EasyDialogs for Windows 46691.0
如果这对你很重要:它使用本地对话框,不像已提到的easygui那样依赖于Tkinter,但可能没有那么多功能。

4

您可以使用pyautoguipymsgbox

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

使用 pymsgbox 就像使用 pyautogui 一样:

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

2

同时,您可以在撤回其他窗口之前将其定位,以便您定位您的消息。

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!")

请注意:这是Lewis Cowles的答案,仅在Python 3中进行了修改,因为tkinter自Python 2以来已经发生了变化。如果您希望您的代码向后兼容,请执行以下操作:
try:
    import tkinter
    import tkinter.messagebox
except ModuleNotFoundError:
    import Tkinter as tkinter
    import tkMessageBox as tkinter.messagebox

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接