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

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

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

我试过 tkMessageBox:

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

但这将在后台打开另一个带有 tk 图标的窗口。我不想这样。我正在寻找一些简单的 wxPython 代码,但它总是需要设置一个类,并进入一个应用程序循环等。难道没有一种简单的方法可以用 Python 创建一个消息框吗?

466442 次浏览

你看过 容易归吗?

import easygui


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

在 Windows 中,可以使用 带有 user32库的 ctype:

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也有一个(基于 ctype 的)窗口版本

如果这对您很重要的话: 它使用本地对话框,并且不像前面提到的 easygui那样依赖于 Tkinter,但是它可能没有那么多的特性。

您呈现的代码很好!你只需要显式地创建“背景中的其他窗口”并隐藏它,用下面的代码:

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

就在你的信箱前面。

此外,您还可以在撤回另一个窗口之前定位它,以便定位您的消息

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

您可以像下面这样使用导入和单行代码:

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

使用

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

之前必须创建主窗口。这是为 Python 3准备的。这不是 wxPython,而是 tkinter。

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

PyMsgBox 模块正是这样做的。它具有消息框函数,遵循 JavaScript 的命名约定: 踪()、确认()、提示()和密码()(提示() ,但在输入时使用 *)。这些函数调用会阻塞,直到用户单击 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/

不是最好的,这是我的基本消息框只使用 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
"""

查看我的 python 模块: pip install Quick gui (需要 wxPython,但不需要 wxPython 知识) Https://pypi.python.org/pypi/quickgui

可以创建任意数量的输入,(比率,复选框,输入框) ,自动安排他们在一个图形用户界面。

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)

会给 这个:

enter image description here

最近的一个消息框版本是师提示框模块。它有两个软件包: 警报和消息。消息使您可以更好地控制框,但需要更长的时间才能输入。

示例警报代码:

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

此外,您还可以在撤回另一个窗口之前定位它,以便定位您的消息

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 3fied,因为 tkinter 自 Python 2以来已经改变了。如果您希望您的代码是可兼容的反向代码,可以这样做:

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

带线程的 ctype 模块

我用的是 Tkinter 留言箱,但它会崩溃我的代码。我不想知道为什么,所以我用 类型模块代替。

例如:

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

我从 阿克里斯拿到了密码


我喜欢它没有崩溃的代码,所以我工作,并添加了一个线程,以后的代码将运行。

我的代码的例子

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

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

我不得不在现有的程序中添加一个消息框。在这种情况下,大多数答案都过于复杂。对于 Ubuntu 16.04上的 Linux (Python 2.7.12)以及 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

另一个好处是,如果父窗口在程序启动后被移动,那么消息框仍然会出现在可预测的位置。

如果您想要一个消息框,将退出,如果不点击时间

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)