回答问题

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

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

我试过 tkMessageBox:

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

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

Answers

您可以使用如下导入和单行代码:

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

Logo

学AI,认准AI Studio!GPU算力,限时免费领,邀请好友解锁更多惊喜福利 >>>

更多推荐