B Bulfin B Bulfin - 2 months ago 23
Python Question

Using python 2 or 3, matplotlib and tkinter causes an extra empty window to open on calling plt.show()

I am making an interactive data analysis tool that I am having trouble with (in

python 2.7
,
3.4
and
3.5
). The full program makes graphs that the user has to interact with and then close. It also requires the user to input files via a filechooser.

The issue is whenever I use
plt.show()
an additional small window opens (which I don't want) along with the graph. The small window then has to be closed too, to continue the program. Not that big a deal, but there are many graphs to interact with, so it is a bit off a pain always closing two windows.

If the
Tkinter.Tk().withraw()
is uncommented only the plot opens, but now the program just hangs upon closing the graph and I have to kill the process.

Any ideas for how I might get around this problem?

Thanks in advance. Example code:

import matplotlib.pyplot as plt
import numpy as np
try:
import Tkinter
except (ImportError):
import tkinter as Tkinter
try:
from tkFileDialog import askopenfilename
except (ImportError):
from tkinter.filedialog import askopenfilename

# Tkinter.Tk().withdraw()

print(askopenfilename())


x = np.arange(0,5,0.1)
y = np.sin(x)

plt.plot(x,y)
plt.show()

Answer

Ok I think I solved it myself after a bit of poking around in the matplotlib source. I tried changing the matplotlib backend to gtk3cairo. I guess the Tk().withdraw() was also affecting the matplotlib backend. Works on my linux distro but still need to test it on windows. If I find a solution that works on both I will update the answer.

EDIT: matplotlib.use("Qt4agg") worked on my windows version. I alo got it work on linux by installing pyside. Doesn't work with the latest version of python3 unfortunatly

Working code:

import matplotlib
matplotlib.use("gtk3cairo")
import matplotlib.pyplot as plt
import numpy as np
try:
    import Tkinter
except (ImportError):
    import tkinter as Tkinter
try:
    from tkFileDialog import askopenfilename
except (ImportError):
    from tkinter.filedialog import askopenfilename

Tkinter.Tk().withdraw()

print(askopenfilename())


x = np.arange(0,5,0.1)
y = np.sin(x)

fig1 = plt.figure()
plt.plot(x,y)
plt.show(fig1)