开发者

Python Message Box Without huge library dependency

开发者 https://www.devze.com 2023-01-31 21:35 出处:网络
Is there a messagebox class where I can just display a simple message box without a huge GUI library or any library upon program suc开发者_如何学运维cess or failure. (My script only does 1 thing).

Is there a messagebox class where I can just display a simple message box without a huge GUI library or any library upon program suc开发者_如何学运维cess or failure. (My script only does 1 thing).

Also, I only need it to run on Windows.


You can use the ctypes library, which comes installed with Python:

import ctypes
MessageBox = ctypes.windll.user32.MessageBoxW
MessageBox(None, 'Hello', 'Window title', 0)

Above code is for Python 3.x. For Python 2.x, use MessageBoxA instead of MessageBoxW as Python 2 uses non-unicode strings by default.


There are also a couple prototyped in the default libraries without using ctypes.

Simple message box:

import win32ui
win32ui.MessageBox("Message", "Title")

Other Options

if win32ui.MessageBox("Message", "Title", win32con.MB_YESNOCANCEL) == win32con.IDYES:
    win32ui.MessageBox("You pressed 'Yes'")

There's also a roughly equivalent one in win32gui and another in win32api. Docs for all appear to be in C:\Python{nn}\Lib\site-packages\PyWin32.chm


The PyMsgBox module uses Python's tkinter, so it doesn't depend on any other third-party modules. You can install it with pip install pymsgbox.

The function names are similar to JavaScript's alert(), confirm(), and prompt() functions:

>>> import pymsgbox
>>> pymsgbox.alert('This is an alert!')
>>> user_response = pymsgbox.prompt('What is your favorite color?')


A quick and dirty way is to call OS and use "zenity" command (subprocess module should be included by default in any python distribution, zenity is also present in all major linux). Try this short example script, it works in my 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)

See the zenity --help for more complex dialogs


You can also use the messagebox class from tkinter: from tkinter import messagebox unless tkinter is that huge GUI you want to avoid. Usage is simple, ie: messagebox.FunctionName(title, message [, options]) with FuntionName in (showinfo, showwarning, showerror, askquestion, askokcancel, askyesno, askretrycancel).


This one with 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.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号