关于wxpython:如何在Python中创建一个简单的消息框?

How can I create a simple message box in Python?

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

我今天下午使用Twisted.web编写了一个基于Web的简单解释器。 您基本上是通过表单提交Python代码块的,客户端来抓取并执行它。 我希望能够发出一个简单的弹出消息,而不必每次都重新编写一堆样板的wxPython或TkInter代码(因为该代码通过表单提交然后消失了)。

我尝试过tkMessageBox:

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

但这会在后台用tk图标打开另一个窗口。 我不要这个 我一直在寻找一些简单的wxPython代码,但它始终需要设置一个类并进入应用程序循环等。在Python中没有简单易行的方法来制作消息框吗?


您可以使用导入和单行代码,如下所示:

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

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

1
2
3
4
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)

注意样式如下:

1
2
3
4
5
6
7
8
##  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

玩得开心!

注意:已编辑为使用MessageBoxW而不是MessageBoxA


你看过easygui了吗?

1
2
3
import easygui

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


另外,您可以在撤消另一个窗口之前先放置它,以便放置消息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/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!")


您提供的代码很好!您只需要使用以下代码显式创建"背景中的其他窗口"并将其隐藏:

1
2
3
import Tkinter
window = Tkinter.Tk()
window.wm_withdraw()

就在您的消息框之前。


PyMsgBox模块正是这样做的。它具有遵循JavaScript命名约定的消息框功能:alert(),confirm(),prompt()和password()(是alert(),但键入时使用*)。这些函数调用将阻塞,直到用户单击"确定" /"取消"按钮为止。这是一个无依赖的跨平台纯Python模块。

安装方式:pip install PyMsgBox

用法示例:

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

完整文档位于http://pymsgbox.readthedocs.org/en/latest/


在Windows中,可以将ctypes与user32库一起使用:

1
2
3
4
5
6
7
8
9
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")

在Mac上,python标准库具有名为EasyDialogs的模块。 http://www.averdevelopment.com/python/EasyDialogs.html上还有一个基于ctypes的Windows版本。

如果对您很重要:它使用本机对话框,并且不像已经提到的easygui那样依赖Tkinter,但是它可能没有那么多功能。


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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
## 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
ctypes.windll.user32.MessageBoxW(0,"That's an error","Warning!", 16)

将给出以下内容:

enter image description here


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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


另外,您可以在撤消另一个窗口之前先放置它,以便放置消息

1
2
3
4
5
6
7
8
9
10
11
12
13
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 3ified的回答,因为tkinter自python 2起就发生了变化。如果您想使代码成为可兼容的backword,请执行以下操作:

1
2
3
4
5
6
try:
    import tkinter
    import tkinter.messagebox
except ModuleNotFoundError:
    import Tkinter as tkinter
    import tkMessageBox as tkinter.messagebox

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

必须先创建主窗口。这是针对Python 3的。这不是wxPython,而是tkinter的。


您可以使用pyautoguipymsgbox

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

使用pymsgbox与使用pyautogui相同:

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

并不是最好的,这是我仅使用tkinter的基本消息框。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#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 Main Window.

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

if __name__ == '__main__':

Return = MsgBox(#Use Like This.
    'Basic Error Exemple',

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

    2,
);

print( Return );

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


签出我的python模块:pip install quickgui(需要wxPython,但不需要wxPython知识)
https://pypi.python.org/pypi/quickgui

可以创建任意数量的输入(比率,复选框,输入框),并自动将它们排列在一个GUI上。


最新的消息框版本是hint_box模块。它有两个软件包:警报和消息。 Message使您可以更好地控制该框,但键入时间会更长。

警报代码示例:

1
2
3
4
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

消息代码示例:

1
2
3
4
5
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

带螺纹的ctype模块

我正在使用tkinter消息框,但它会使我的代码崩溃。我不想找出原因,所以我改用ctypes模块。

例如:

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

我从Arkelis那里得到了那个代码

我喜欢它不会使代码崩溃,所以我对其进行了处理并添加了线程,以便随后的代码可以运行。

我的代码示例

1
2
3
4
5
6
7
8
9
10
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)

对于按钮样式和图标编号:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
## 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