在 Mac 上的 Python 中创建消息框?

2024-01-16

目前正在学习 Cybrary 的免费 Python 在线课程(我正在使用 3.6 进行编码),但我使用的是 Mac,而演示者使用的是 Windows。到目前为止,如果有的话,差异也很小。

然而,当前部分涉及学习和使用 Ctypes,“作业”说的是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)

My code:

# 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), use:

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"'

See here https://stackoverflow.com/a/28749940/2836621获取更多示例。

所以,只需使用 Python 子进程调用来运行它......子流程文档 https://docs.python.org/3/library/subprocess.html,或使用system().

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Mac 上的 Python 中创建消息框? 的相关文章

随机推荐