如何在Python中创建一个简单的消息框?

2024-04-27 00:01:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找与JavaScript中的alert()相同的效果。

今天下午我用Twisted.web编写了一个简单的基于web的解释器。您基本上是通过表单提交一块Python代码,然后客户端来获取并执行它。我希望能够制作一个简单的弹出消息,而不必每次都重新编写一大堆样板wxPython或TkInter代码(因为代码通过表单提交然后消失)。

我试过tkMessageBox:

import tkMessageBox
tkMessageBox.showinfo(title="Greetings", message="Hello World!")

但这会在背景中打开另一个带有tk图标的窗口。我不想要这个。我在寻找一些简单的wxPython代码,但它总是需要设置一个类并输入一个应用程序循环等。难道没有简单的、无捕获的方法在Python中创建一个消息框吗?


Tags: 代码web消息客户端表单tkinterwxpythontwisted
3条回答

你看过easygui了吗?

import easygui

easygui.msgbox("This is a message!", title="simple gui")

另外,您还可以在撤回前定位另一个窗口,以便定位您的消息

#!/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!")

您可以使用这样的导入和单行代码:

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

相关问题 更多 >