如何在Python中创建简单的消息框?
我想要在JavaScript中实现和alert()一样的效果。
今天下午我用Twisted Web写了一个简单的网页解释器。你基本上是通过一个表单提交一段Python代码,然后客户端会把这段代码拿过来执行。我想要能够简单地弹出一个消息框,而不需要每次都重写一大堆wxPython或Tkinter的代码(因为代码是通过表单提交的,然后就消失了)。
我试过用tkMessageBox
:
import tkMessageBox
tkMessageBox.showinfo(title="Greetings", message="Hello, World!")
但是这会在后台打开另一个窗口,并显示Tkinter的图标。我不想要这个。我在找一些简单的wxPython代码,但它总是需要设置一个类并进入一个应用循环等等。难道没有一种简单的方法可以在Python中创建一个消息框吗?
18 个回答
23
你提供的代码没问题!你只需要明确地创建一个“在后台的其他窗口”,然后把它隐藏起来,使用下面的代码:
import Tkinter
window = Tkinter.Tk()
window.wm_withdraw()
这段代码要放在你的消息框之前。
62
你有没有看过easygui这个东西?
import easygui
easygui.msgbox("This is a message!", title="simple gui")
367
你可以用一个导入和一行代码来实现,像这样:
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 | Cancel
## 6 : Cancel | Try Again | Continue
玩得开心!
注意:已经修改为使用 MessageBoxW
而不是 MessageBoxA