Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the Mac "command" symbol in a Tkinter menu

I've written a Python program for a friend's business, and am using Tkinter for the interface. Up until now, all features have been added in the main program window, but I'm now adding a print feature, have created a simple "File" menu, and want to add a "Print" entry to that menu, including displaying the relevant keyboard shortcut.

On my Mac, I want the shortcut to be Command-P. I found the Mac "command" symbol's Unicode value, and have tried various ways to create an accelerator string that simply concatenates that symbol and the letter "P", but nothing works. I get either the symbol or the letter to display in the menu next to "Print", but never both.

Here is the full line of code that adds the menu item, with the latest attempt at building the string (I believe I found this unicode.join option elsewhere in Stack Overflow):

sub_menu.add_command(label="Print", command=self.print_, accelerator=unicode.join(u"\u2318", u"P"))
// Only the "P" displays

Here are some of the other options that I've tried (lines truncated for clarity). With each of these options, only the "command" symbol appears:

accelerator=u"\u2318\u0050"
accelerator=u"\u2318" + "P"
accelerator=u"\u2318" + u"P"
accelerator=u"\u2318P"
accelerator=u"".join([u"\u2318", u"P"])

Up until now I haven't had a need to learn much about Unicode strings, so perhaps there's something I'm doing wrong in that regard. However, all of the attempts that I've made have come as a result of various searches, both here and elsewhere, and so far nothing has worked. Any insight into how to make this work would be most welcome!

Python 2.7.3, Mac OS X 10.8.3

like image 438
Justin S Barrett Avatar asked Oct 21 '22 08:10

Justin S Barrett


1 Answers

After further searching online, I finally found a page that has the solution. I was surprised (and a touch annoyed) that this solution was different than the one outlined in the PDF documentation for Tkinter 8.4 that I've been referencing thus far (the one published by New Mexico Tech). I found links to Tkinter 8.5 documentation, but they also list the incorrect process.

Anyway, it's a lot simpler than I thought, and is similar to the syntax used for key binding, but slightly different. Instead of directly including the command symbol in the accelerator string, Tkinter takes the literal word "Command" (or the abbreviated "Cmd"), and internally converts it to the displayable character "⌘" in the menu. So my resulting line is:

sub_menu.add_command(label="Print", command=self.print_, accelerator="Command-P")

...and what I get in my full menu item is:

Print ⌘P

As the page linked above shows, similar shortcut words exist for other modifier keys, and on Mac OS X, these are all automatically translated into their graphical equivalents.

like image 160
Justin S Barrett Avatar answered Oct 31 '22 18:10

Justin S Barrett