美好的一天,
我制作了一个程序来进行测量并将其绘制在图形上。然后,借助QFileDialog,用户可以在具有自定义名称的自定义位置将数据导出为.csv或将图形导出为.png。下面是代码,任何人都可以自己使用它。
我的问题是:如何在对话框中预填充文件名,以便用户仍然可以指定自定义名称,但是如果他们不在乎它已经填充了实验参数。提前致谢。
def export_picture(self):
"""Grabs the plot on the interface and saves it in a .png file at a custom location."""
# Setup a file dialog.
MyDialog = QFileDialog()
MyDialog.setWindowTitle("Select a location to save your graph.")
MyDialog.setAcceptMode(QFileDialog.AcceptSave)
# MyDialog.a_method_to_prefill_the_file_name("name") <-- ?
MyDialog.exec_()
# Abort the function if somebody closed the file dialog without selecting anything.
if len(MyDialog.selectedFiles()) == 0:
return
# Save the file and notify the user.
CompleteName = MyDialog.selectedFiles()[0] + ".png"
self.ui.Graph.figure.savefig(fname=CompleteName, dpi=254, format="png")
Directory, File = os.path.split(FileAndPath)
print('Graph exported as "%s.png" in the folder "%s".' %(File, Directory))
答案 0 :(得分:0)
您可以使用getSaveFileName。
import sys
from PyQt5 import QtWidgets
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
button = QtWidgets.QPushButton('Get File Name...')
button.show()
def _get_file_name():
save_file, _ = QtWidgets.QFileDialog.getSaveFileName(button, "Save File...", 'foo.txt')
print(f'save_file = {save_file}')
button.clicked.connect(_get_file_name)
sys.exit(app.exec_())