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

时间:2010-06-03 04:07:21

标签: python wxpython tkinter

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

我今天下午用Twisted.web写了一个简单的基于网络的翻译。你基本上通过一个表单提交一个Python代码块,然后客户端来抓取它并执行它。我希望能够制作一个简单的弹出消息,而不必每次都重写一大堆样板wxPython或TkInter代码(因为代码通过表单提交然后消失)。

我尝试过tkMessageBox:

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

但这会在背景中打开另一个带有tk图标的窗口。我不想要这个。我一直在寻找一些简单的wxPython代码,但它总是需要设置一个类并进入一个应用程序循环等。在Python中没有简单,无需捕获的方法来制作消息框吗?

17 个答案:

答案 0 :(得分:198)

你可以使用像这样的导入和单行代码:

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 | No 
##  6 : Cancel | Try Again | Continue

玩得开心!

注意:已修​​改为使用MessageBoxW代替MessageBoxA

答案 1 :(得分:47)

你看过easygui吗?

import easygui

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

答案 2 :(得分:21)

此外,您可以在退出之前定位另一个窗口,以便您定位消息

#!/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 :(得分:19)

您提供的代码很好!您只需要在后台显式创建“其他窗口”并使用以下代码隐藏它:

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

就在你的留言箱之前。

答案 4 :(得分:9)

在Windows中,您可以使用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")

答案 5 :(得分:9)

在Mac上,python标准库有一个名为EasyDialogs的模块。在http://www.averdevelopment.com/python/EasyDialogs.html

还有一个(基于ctypes的)Windows版本

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

答案 6 :(得分:7)

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

安装时使用: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/

的完整文档

答案 7 :(得分:5)

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

答案 8 :(得分: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 

答案 9 :(得分:1)

使用

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

之前必须创建主窗口。这适用于Python 3.这不是fot wxPython,而是tkinter。

答案 10 :(得分:1)

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

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,请执行以下操作:

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

答案 11 :(得分:0)

不是最好的,这是我只使用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 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',                      '\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 );

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

答案 12 :(得分:0)

check out my python module: pip install quickgui (Requires wxPython, but requires no knowledge of wxPython) https://pypi.python.org/pypi/quickgui

Can create any numbers of inputs,(ratio, checkbox, inputbox), auto arrange them on a single gui.

答案 13 :(得分:0)

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

示例警报代码:

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

示例消息代码:

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

答案 14 :(得分:0)

带有线程的ctype模块

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

例如:

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

我从 Arkelis

获得了该代码

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

我的代码示例

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)

有关按钮样式和图标编号:

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

答案 15 :(得分:0)

您可以使用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")

答案 16 :(得分:0)

我必须在现有程序中添加一个消息框。在这种情况下,大多数答案都过于复杂。对于Ubuntu 16.04(Python 2.7.12)上的Linux,以及适用于Ubuntu 20.04的将来的证明,这是我的代码:

程序顶部

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"

无论运行哪个Python版本,代码都将始终为messagebox.,以供将来校对或向后兼容。我只需要在上面的现有代码中插入两行即可。

使用父窗口几何图形的消息框

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

如果歌曲计数为零,我已经有返回代码。因此,我只需要在现有代码之间插入三行。

您可以通过使用父窗口引用来避免复杂的几何代码:

parent=self.toplevel

另一个优点是,如果在程序启动后移动了父窗口,则您的消息框仍会出现在可预测的位置。