3

I am trying to create a simple file selection dialog for one of my scripts and I was trying to use the code examples from this thread: Quick and easy file dialog in Python?

import Tkinter, tkFileDialog

root = Tkinter.Tk()
root.withdraw()

file_path = tkFileDialog.askopenfilename()

I also tried using the easygui module that uses Tkinter to do the same thing. In both cases, the code above hangs the IPython console. I gather that this has something to do with event loops, but I have no real experience with GUIs in Python.

Could someone point me in the right direction on how to get a dialogbox for file selection to work with IPython/Spyder. For the record, I am on Python 2.7.6 and IPython 2.4.1

Community
  • 1
  • 1
HamsterHuey
  • 1,093
  • 9
  • 11

1 Answers1

1

Before running the code above, you need to set the right event loop (in this case Tk), as you correctly guessed.

To do that you need to run this command:

In [1]: %gui tk

and then run your code.

Note: To access the documentation about the %gui magic in Spyder, you need to place the cursor in front of %gui and press Ctrl+I, like this

In [1]: %gui<Ctrl+I>
Carlos Cordoba
  • 27,745
  • 9
  • 78
  • 109
  • I'm not at my work computer to try it, but on my desktop at home, I just tried `%gui tk` in the IPython console within Spyder (Spyder 2.3.4) and I get the following error message: "ERROR: Cannot activate multiple GUI eventloops" I did try this in IPython QtConsole and it worked without the error message. Is there something special I need to change in Spyder settings to get the `%gui` command to work for tkinter? – HamsterHuey Jun 03 '15 at 02:13
  • That's because you have another backend selected to create plots (probably `qt` or `automatic`) in the Spyder preferences. To make `%gui tk` work in this case, you need to run first `%gui inline`. This is a little trick to change backends in the same session with seeing that error. – Carlos Cordoba Jun 03 '15 at 03:16
  • I also forget to mention that if you want to make `tk` your default backend for all consoles, you need to go to `Tools > Preferences > IPython Console > Graphics > Graphics backend` and select `Tk` there. – Carlos Cordoba Jun 03 '15 at 03:19