What I want to do
I am trying to make an interactive plot for a Jupyter Notebook. The functions are all written in different files, but their intended use is in interactive notebook sessions. I have a Button widget on a matplotlib figure, which, when clicked, I want to open a file dialog where a user can enter a filename to save the figure to. I am on Mac OSX (Mojave 10.14.6) and Tkinter is giving me major problems (complete system crashes), so I am trying to implement this with PyQt5.
The code
-----------
plotting.py
-----------
from . import file_dialog as fdo
import matplotlib.pyplot as plt
import matplotlib.widgets as wdgts
def plot_stack(stack):
fig, ax = plt.subplots(figsize=(8, 6))
plt.subplots_adjust(bottom=0.25, left=-0.1)
... # plotting happens here
# button for saving
def dosaveframe(event):
fname = fdo.save()
fig.savefig(fname) # to be changed to something more appropriate
savea = plt.axes([0.65, 0.8, 0.15, 0.05], facecolor=axcolor)
saveb = Button(savea, "save frame", hovercolor="yellow")
saveb.on_clicked(dosaveframe)
savea._button = saveb # for persistence
plt.show()
--------------
file_dialog.py
--------------
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import (QWidget, QFileDialog)
class SaveFileDialog(QWidget):
def __init__(self, text="Save file", types="All Files (*)"):
super().__init__()
self.title = text
self.setWindowTitle(self.title)
self.types = types
self.filename = self.saveFileDialog()
self.show()
def saveFileDialog(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
filename, _ = (
QFileDialog.getSaveFileName(self, "Enter filename",
self.types, options=options))
return filename
def save(directory='./', filters="All files (*)"):
"""Open a save file dialog"""
app = QApplication([directory])
ex = SaveFileDialog(types=filters)
return ex.filename
sys.exit(app.exec_())
What is not working
The save dialog opens and it responds to the mouse, but not to the keyboard. The keyboard stays connected to the notebook no matter if I select the little window, so when I press "s" it saves the notebook. As such, the user can not enter a file path. How can I make this work? I have Anaconda, PyQt 5.9.2, matplotlib 3.1.1, jupyter 1.0.0.