EDIT: This seems to be a problem restricted to Tcl/Tk on Mac OS systems. So if you have no experience with that, this topic might be moot...
I want to have a Python script that does two things:
- Ask the user for a file name via a Tkinter file dialog.
- Plot some data from said file.
The problem is, matplotlib uses Tkinter for the graphical representations, and whenever I call pyplot.show()
in non-interactive mode, the (before closed) file dialog pops up again. It seems to me like pyplot.show()
gathers a list of all Tkinter windows and shows them all. I did not find any help on this however. I tried for both Python 2.7 and 3.3, since a lot of the Tkinter module seems to have changed, but it's the same phenomenon. The slightly strange workaround I came up with is to go into matplotlib interactive mode and then keep the windows open with a raw_input()
command.
Here is a minimal code snippet that works in Python 2 and 3 to show the problem:
import matplotlib.pyplot as plt
# import Tkinter GUI (changes from Python 2.x to 3.x)
try:
import Tkinter
except (ImportError):
import tkinter as Tkinter
try:
from tkFileDialog import askopenfilename
except (ImportError):
from tkinter.filedialog import askopenfilename
root = Tkinter.Tk()
root.withdraw()
input_filename = askopenfilename(master=root)
# This seemed promising, but it doesn't help
root.destroy()
plt.figure()
# uncommenting this to switch to interactive mode is a workaround
#plt.ion()
plt.show()
# Python 2.x and 3.x compatible wait for input:
try: input = raw_input
except NameError: pass
# Wait for keystroke (for interactive mode)
input("Press enter when done...")
I'm sorry if I'm missing something obvious here, I am not that well-versed in Python, and I did not find satisfying information on this problem. But my gutt tells me there has to be a simple and elegant solution for this.
System information (most recent versions I tried):
- Python 3.3 (from MacPorts)
- matplotlib 1.3.x (built from github master)
- Mac OS X 10.8.3
- Tcl/Tk 8.6.0 (from MacPorts)
Thanks,
Floh