Python 消息框没有巨大的库依赖

问题描述 投票:0回答:6

是否有一个消息框类,我可以在其中显示一个简单的消息框,而无需庞大的 GUI 库或程序成功或失败时的任何库。 (我的脚本只做了一件事)。

另外,我只需要它在 Windows 上运行。

python windows user-interface windows-7
6个回答
87
投票

您可以使用随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 字符串。


18
投票

默认库中还有一些原型没有使用 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


6
投票

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

2
投票

一种快速而肮脏的方法是调用操作系统并使用“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 了解更复杂的对话框


2
投票

您还可以使用 tkinter 中的 messagebox 类:

from tkinter import messagebox
除非 tkinter 是您想要避免的那种巨大的 GUI。 使用方法很简单,即:
messagebox.FunctionName(title, message [, options])
在(showinfo、showwarning、showerror、askquestion、askokcancel、askyesno、askretrycancel)中使用FuntionName。


1
投票

这个是 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.
© www.soinside.com 2019 - 2024. All rights reserved.