[Tkinter-discuss] tkFileDialog.askopenfile() mac

JBB jeanbigboute at gmail.com
Wed Aug 13 06:05:16 CEST 2014


On 8/12/14, 7:19 PM, Kevin Walzer wrote:
> Hi,
> On 8/12/14, 10:23 AM, JBB wrote:
>> After some more digging, I find that Python uses the macosx backend on
>> initialization.  If I change this to tk before beginning work, the
>> problem goes away.  My Linux Python uses tk by default.
> What do you mean by this? On Mac, Tkinter/Tk uses native dialogs and
> widgets by default. What change did you make to get it to work on the Mac?

Thank you for the suggestions.  My notes:

I normally use the iPython Notebook for my Python coding.  As a newcomer 
to the language, the self-documenting features are helpful.

The following code works in the notebook:  A file dialog (native Mac) 
comes up, I can navigate, select a file, the dialog box closes, and the 
correct path and filename print.

%matplotlib tk
from Tkinter import *
import tkFileDialog
root = Tk()
filename = tkFileDialog.askopenfilename(parent=root)
print filename

If I don't have the initial magic command, the file dialog box hangs 
after file selection.  The rainbow ball just spins until I restart the 
kernel at which point it closes.

I normally invoke the notebook with
ipython notebook
%matplotlib at the first cell gives
Using matplotlib backend: MacOSX

I can't change the backend at this point so I have to restart the kernel 
and make sure to run %matplotlib tk before any imports.

This is a convenient albeit slightly kludgy way of setting the backend.

If I invoke the notebook with:
ipython notebook --matplotlib=tk

then the code above _without_ the %magic command works fine.

> I did see the dialog hanging on the Mac. My guess is that you weren't
> giving the event loop enough time to spin; the dialog was popping up too
> fast. This code works just fine:
> from Tkinter import *
> import tkFileDialog
> root = Tk()
> def openfile():
>      tkFileDialog.askopenfilename(parent=root)
> b = Button(root, text="Open", command=openfile).pack()
> root.mainloop()

I tried this in a fresh notebook.

A small window opens, when I mouseover, an Open button appears.  I click 
it, I get a native Mac file dialog box.  I navigate, select a file, the 
dialog box disappears and the small window/button remain.  The kernel on 
the notebook shows busy until I close the small window.

I'm not up on the Button and .pack tools as yet.  I don't know where the 
filename is stored.


More information about the Tkinter-discuss mailing list