问题:如何在Python中创建一个简单的消息框?
我正在寻找与alert()
JavaScript 相同的效果。
我今天下午使用Twisted.web编写了一个基于Web的简单解释器。您基本上是通过表单提交Python代码块的,客户端来抓取并执行它。我希望能够做出一个简单的弹出消息,而不必每次都重写一堆样板的wxPython或TkInter代码(因为该代码是通过表单提交的,然后消失了)。
我尝试过tkMessageBox:
import tkMessageBox
tkMessageBox . showinfo ( title = "Greetings" , message = "Hello World!" )
但这会在后台用tk图标打开另一个窗口。我不要这个 我一直在寻找一些简单的wxPython代码,但是它总是需要设置一个类并进入应用程序循环等。在Python中没有简单易行的方法来制作消息框吗?
I’m looking for the same effect as alert()
in JavaScript.
I wrote a simple web-based interpreter this afternoon using Twisted.web. You basically submit a block of Python code through a form, and the client comes and grabs it and executes it. I want to be able to make a simple popup message, without having to re-write a whole bunch of boilerplate wxPython or TkInter code every time (since the code gets submitted through a form and then disappears).
I’ve tried tkMessageBox:
import tkMessageBox
tkMessageBox.showinfo(title="Greetings", message="Hello World!")
but this opens another window in the background with a tk icon. I don’t want this. I was looking for some simple wxPython code but it always required setting up a class and entering an app loop etc. Is there no simple, catch-free way of making a message box in Python?
回答 0
您可以使用导入和单行代码,如下所示:
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 | No
## 6 : Cancel | Try Again | Continue
玩得开心!
注意:已编辑以MessageBoxW
代替MessageBoxA
You could use an import and single line code like this:
import ctypes # An included library with Python install.
ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 1)
Or define a function (Mbox) like so:
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)
Note the styles are as follows:
## 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
Have fun!
Note: edited to use MessageBoxW
instead of MessageBoxA
回答 1
你看过easygui 吗?
import easygui
easygui . msgbox ( "This is a message!" , title = "simple gui" )
Have you looked at easygui ?
import easygui
easygui.msgbox("This is a message!", title="simple gui")
回答 2
另外,您可以在撤消另一个窗口之前先放置它,以便放置消息
#!/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!" )
Also you can position the other window before withdrawing it so that you position your message
#!/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!")
回答 3
您提供的代码很好!您只需要使用以下代码显式创建“背景中的其他窗口”并将其隐藏:
import Tkinter
window = Tkinter . Tk ()
window . wm_withdraw ()
就在您的消息框之前。
The code you presented is fine! You just need to explicitly create the “other window in the background” and hide it, with this code:
import Tkinter
window = Tkinter.Tk()
window.wm_withdraw()
Right before your messagebox.
回答 4
PyMsgBox模块正是这样做的。它具有遵循JavaScript命名约定的消息框功能:alert(),confirm(),prompt()和password()(后者是hint(),但键入时使用*)。这些函数调用将阻塞,直到用户单击“确定” /“取消”按钮为止。这是一个无依赖的跨平台纯Python模块。
安装方式: 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/
The PyMsgBox module does exactly this. It has message box functions that follow the naming conventions of JavaScript: alert(), confirm(), prompt() and password() (which is prompt() but uses * when you type). These function calls block until the user clicks an OK/Cancel button. It’s a cross-platform, pure Python module with no dependencies.
Install with: pip install PyMsgBox
Sample usage:
import pymsgbox
pymsgbox.alert('This is an alert!', 'Title')
response = pymsgbox.prompt('What is your name?')
Full documentation at http://pymsgbox.readthedocs.org/en/latest/
回答 5
在Windows中,可以将ctypes与user32库一起 使用:
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" )
In Windows, you can use ctypes with user32 library :
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")
回答 6
On Mac, the python standard library has a module called EasyDialogs
. There is also a (ctypes based) windows version at http://www.averdevelopment.com/python/EasyDialogs.html
If it matters to you: it uses native dialogs and doesn’t depend on Tkinter like the already mentioned easygui
, but it might not have as much features.
回答 7
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 )
会给这个 :
import ctypes
ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 1)
The last number (here 1) can be change to change window style (not only buttons!):
## 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
For example,
ctypes.windll.user32.MessageBoxW(0, "That's an error", "Warning!", 16)
will give this :
回答 8
用
from tkinter . messagebox import *
Message ([ master ], title = "[title]" , message = "[message]" )
必须先创建主窗口。这是针对Python 3的。这不是wxPython,而是tkinter的。
Use
from tkinter.messagebox import *
Message([master], title="[title]", message="[message]")
The master window has to be created before. This is for Python 3. This is not fot wxPython, but for tkinter.
回答 9
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
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
回答 10
另外,您可以在撤消另一个窗口之前先放置它,以便放置消息
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 3ified,因为tkinter自python 2起就发生了变化。
try :
import tkinter
import tkinter . messagebox
except ModuleNotFoundError :
import Tkinter as tkinter
import tkMessageBox as tkinter . messagebox
Also you can position the other window before withdrawing it so that you position your message
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!")
Please Note: This is Lewis Cowles’ answer just Python 3ified, since tkinter has changed since python 2. If you want your code to be backwords compadible do something like this:
try:
import tkinter
import tkinter.messagebox
except ModuleNotFoundError:
import Tkinter as tkinter
import tkMessageBox as tkinter.messagebox
回答 11
并不是最好的,这是我仅使用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
"""
Not the best, here is my basic Message box using only 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
"""
回答 12
check out my python module: pip install quickgui (Requires wxPython, but requires no knowledge of wxPython)
https://pypi.python.org/pypi/quickgui
Can create any numbers of inputs,(ratio, checkbox, inputbox), auto arrange them on a single gui.
回答 13
最新的消息框版本是hint_box模块。它有两个软件包:警报和消息。Message使您可以更好地控制该框,但键入时间会更长。
警报代码示例:
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
A recent message box version is the prompt_box module. It has two packages: alert and message. Message gives you greater control over the box, but takes longer to type up.
Example Alert code:
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
Example Message code:
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
回答 14
带螺纹的ctype模块
我正在使用tkinter消息框,但它会使我的代码崩溃。我不想找出原因,所以我改用ctypes 模块。
例如:
import ctypes
ctypes . windll . user32 . MessageBoxW ( 0 , "Your text" , "Your title" , 1 )
我从Arkelis 那里得到了那个代码
我喜欢它不会使代码崩溃,因此我对其进行了工作并添加了线程,以便随后的代码可以运行。
我的代码示例
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
ctype module with threading
i was using the tkinter messagebox but it would crash my code. i didn’t want to find out why so i used the ctypes module instead.
for example:
import ctypes
ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 1)
i got that code from Arkelis
i liked that it didn’t crash the code so i worked on it and added a threading so the code after would run.
example for my code
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)
for button styles and icon numbers:
## 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
回答 15
您可以使用pyautogui
或pymsgbox
:
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" )
You can use pyautogui
or pymsgbox
:
import pyautogui
pyautogui.alert("This is a message box",title="Hello World")
Using pymsgbox
is the same as using pyautogui
:
import pymsgbox
pymsgbox.alert("This is a message box",title="Hello World")