在 Python 中为 Mac 创建 MessageBox?

Create a MessageBox in Python for Mac?

目前正在为来自 Cybrary 的 Python 免费在线 class 工作(我在 3.6 中编码),但我使用 Mac 而演示者使用 Windows.到目前为止,几乎没有差异。

然而,当前部分涉及学习和使用 Ctypes,"assignment" 说到 Write a function which takes two arguments, title and body and creates a MessageBox with those arguments

视频中使用的代码作为创建消息框的示例:

from ctypes import *

windll.user32.MessageBoxA(0, "Click Yes or No\n", "This is a title\n", 4)

我的代码:

# 2.1 Ctypes: Write a function which takes two arguments, title and body
#  and creates a MessageBox with those arguments
def python_message_box(title, body):
    return windll.user32.MessageBoxA(0, body, title, 0)

运行 这给出了错误:

File ".../AdvancedActivities.py", line 9, in python_message_box
   return windll.user32.MessageBoxA(0, body, title, 0)
NameError: name 'windll' is not defined

我不相信我需要说我在尝试 运行

时遇到了同样的错误
windll.user32.MessageBoxW(0, body, title, 0)

我无法在任何地方找到人们在 Mac 台计算机上创建消息框的任何示例。它是 Windows 特定的函数吗?如果是这样,Mac 相当于什么?

编辑:Mark Setchell 的解决方案是使用 Python 运行 终端功能来完成 windll 任务,因此不要使用 windll.user32.MessageBoxA(0, body, title, 0),而是使用:

command = "osascript -e 'Tell application \"System Events\" to
           display dialog \""+body+"\"'"
system(command)

如果您在任何 Mac 上的终端中键入此内容,您将看到一个对话框:

osascript -e 'Tell application "System Events" to display dialog "Some Funky Message" with title "Hello Matey"'

有关更多示例,请参阅 here

因此,只需对 运行 使用 Python 子进程调用... subprocess documentation,或使用 system().

无需安装。没有依赖性。您还可以向用户询问值、select 文件或目录,并使用相同的技术选择颜色。对话框都是原生的 Mac - 不是一些丑陋的模仿。

import os

body_Str="Body of Dialog"

title_Str="Title"

os.system("""osascript -e \'Tell application \"System Events\" to display dialog \""+body_Str+"\" with title \""+title_Str+"\"\'""")

这样好多了