有没有一个消息框类,我可以只显示一个简单的消息框没有一个巨大的图书馆或任何程序库成功或失败的图书馆。 (我的脚本只做1件事)。
另外,我只需要它在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,另一个在win32api中。 所有文档似乎都在C:\Python{nn}\Lib\site-packages\PyWin32.chm
一个快速和肮脏的方法是调用操作系统,并使用“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 – 帮助更复杂的对话框
你也可以使用tkinter的messagebox类: from tkinter import messagebox
除非tkinter是你想要避免的巨大的GUI。 用法很简单,例如:在(showinfo,showwarning,showerror,askquestion,askokcancel,askyesno,askretrycancel)中带有FuntionName的messagebox.FunctionName(title, message [, options])
)。
PyMsgBox模块使用Python的tkinter,所以它不依赖于任何其他的第三方模块。 你可以用pip install pymsgbox
来安装它。
函数名称与JavaScript的alert()
, confirm()
和prompt()
函数类似:
>>> import pymsgbox >>> pymsgbox.alert('This is an alert!') >>> user_response = pymsgbox('What is your favorite color?')