是否有一个消息框类,我可以在其中显示一个简单的消息框,而无需庞大的 GUI 库或程序成功或失败时的任何库。 (我的脚本只做了一件事)。
另外,我只需要它在 Windows 上运行。
您可以使用随Python一起安装的ctypes库:
import ctypes
MessageBox = ctypes.windll.user32.MessageBoxW
MessageBox(None, 'Hello', 'Window title', 0)
以上代码适用于 Python 3.x。对于 Python 2.x,请使用
MessageBoxA
而不是 MessageBoxW
,因为 Python 2 默认情况下使用非 unicode 字符串。
默认库中还有一些原型没有使用 ctypes。
简单的消息框:
import win32ui
win32ui.MessageBox("Message", "Title")
其他选项
if win32ui.MessageBox("Message", "Title", win32con.MB_YESNOCANCEL) == win32con.IDYES:
win32ui.MessageBox("You pressed 'Yes'")
win32gui 中也有一个大致相同的函数,win32api 中也有另一个函数。所有文档似乎都在
C:\Python{nn}\Lib\site-packages\PyWin32.chm
PyMsgBox 模块使用 Python 的 tkinter,因此它不依赖于任何其他第三方模块。您可以使用
pip install pymsgbox
安装它。它适用于 Windows、macOS 和 Linux。
函数名称与 JavaScript 的
alert()
、confirm()
和 prompt()
函数类似:
>>> import pymsgbox
>>> pymsgbox.alert('This is an alert!')
>>> user_response = pymsgbox.prompt('What is your favorite color?')
一种快速而肮脏的方法是调用操作系统并使用“zenity”命令(子进程模块应该默认包含在任何 python 发行版中,zenity 也存在于所有主要 Linux 中)。尝试这个简短的示例脚本,它可以在我的 Ubuntu 14.04 中运行。
import subprocess as SP
# call an OS subprocess $ zenity --entry --text "some text"
# (this will ask OS to open a window with the dialog)
res=SP.Popen(['zenity','--entry','--text',
'please write some text'], stdout=SP.PIPE)
# get the user input string back
usertext=str(res.communicate()[0][:-1])
# adjust user input string
text=usertext[2:-1]
print("I got this text from the user: %s"%text)
请参阅 zenity --help 了解更复杂的对话框
您还可以使用 tkinter 中的 messagebox 类:
from tkinter import messagebox
除非 tkinter 是您想要避免的那种巨大的 GUI。
使用方法很简单,即:
messagebox.FunctionName(title, message [, options])
在(showinfo、showwarning、showerror、askquestion、askokcancel、askyesno、askretrycancel)中使用FuntionName。
这个是 tkinter 的。
from tkinter import * #required.
from tkinter import messagebox #for messagebox.
App = Tk() #required.
App.withdraw() #for hide window.
print("Message Box in Console")
messagebox.showinfo("Notification", "Hello World!") #msgbox
App.mainloop() #required.