Create a MessageBox in Python for Mac?

岁酱吖の 提交于 2020-06-13 00:14:38

问题


Currently working through a free online class for Python from Cybrary (I'm coding in 3.6), but I use a Mac while the presenter uses Windows. So far, there have been very few differences if any.

The current section deals with learning and using Ctypes however, and the "assignment" says to Write a function which takes two arguments, title and body and creates a MessageBox with those arguments.

The code used in the video as an example of creating a Message Box:

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)

Running this gives the error:

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

I don't believe I need to say that I get the same error trying to run

windll.user32.MessageBoxW(0, body, title, 0)

I haven't been able to find any examples anywhere of people creating Message Boxes on Mac computers. Is it a Windows-specific function? If so, what would be the Mac equivalent of this?

EDIT: Mark Setchell's solution is to have Python run terminal functions that accomplish windll tasks, so instead of windll.user32.MessageBoxA(0, body, title, 0), use:

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

回答1:


If you type this into a Terminal on any Mac, you'll get a dialog box:

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

See here for further examples.

So, just use a Python subprocess call to run that... subprocess documentation, or use system().

Nothing to install. No dependencies. You can also ask user for values, select files or directories and pick colours using the same technique. The dialog boxes are all native Mac ones - not some ugly imitation.




回答2:


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+"\"\'""")

this is much better



来源:https://stackoverflow.com/questions/50497479/create-a-messagebox-in-python-for-mac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!