import tkinter
import tkinter.filedialog
import tkinter.messagebox
root=tkinter.Tk()
root.withdraw()
fTyp=[('テキストファイルとExcelファイル','*.txt;*.csv')]
filename=tkinter.filedialog.askopenfilename(filetypes=fTyp)
print(filename)
from PyQt4 import QtGui, QtCore
import os
class MainDialog(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QDialog.__init__(self, None, QtCore.Qt.WindowStaysOnTopHint)
self.setLayout(QtGui.QVBoxLayout())
def open_filedialog(self):
fname = QtGui.QFileDialog.getOpenFileName(self, 'Open file', os.getcwd())
return fname
def save_filedialog(self):
fname = QtGui.QFileDialog.getSaveFileName(self, 'Save file', os.getcwd())
return fname
def open_directory(self):
dname=QtGui.QFileDialog.getExistingDirectory(self, '作業フォルダ', os.getcwd())
return dname
def __create_window():
"""Create a Qt window in Python, or interactively in IPython with Qt GUI
event loop integration.
"""
app = QtCore.QCoreApplication.instance()
app.references = set()
window = MainDialog()
app.references.add(window)
#window.show()
return window
def 開くファイル名():
window=__create_window()
fname=window.open_filedialog()
window.accept()
return fname
def 保存するファイル名():
window=__create_window()
fname=window.save_filedialog()
window.accept()
return fname
def 現在の作業フォルダ():
return os.getcwd()
def 作業フォルダの変更():
window=__create_window()
dname=window.open_directory()
window.accept()
if os.path.isdir(dname):
os.chdir(dname)
return 現在の作業フォルダ()
else:
print( "作業フォルダは変更していません。")
return 現在の作業フォルダ()
ipython notebookでドラッグアンドドロップでファイルを開く事はできません。
make_and_return_window()
を使えばほぼOKでした。
Notebookのセルで%gui qt
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import QMainWindow
def make_and_return_window():
win = QtGui.QMainWindow()
return win
window =make_and_return_window()
window.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
window.show()
とすれば空のQt窓が最前面に現れました。
Ipythonに関する情報がNotebookで必要十分なのかはやってみないと分からない感じですね。app.references.add(window)
をやらないと、windowsがメモリーから消えてしまう可能性があるのだろうか。
windowをcloseした後、再びshowするような使い方をする際には気をつけた方が良いのかも知れません。
ipython notebookでドラッグアンドドロップでファイルを開く事はできません。ただ、にあるように簡単にファイル(複数も可)を選択するGUIが作れるので、実用的にはあまり問題ないと思います。私はpython2.7ではなくpython3.4を使っているので、以下のような多少の書き換えが必要でした。import tkinter
import tkinter.filedialog
import tkinter.messagebox
root=tkinter.Tk()
root.withdraw()
fTyp=[('テキストファイルとExcelファイル','*.txt;*.csv')]
filename=tkinter.filedialog.askopenfilename(filetypes=fTyp)
print(filename)また、ファイルを開くダイアログが前面に出てこないので、Alt+Tabで手前にする必要があります。(Windowsユーザーです。)以前は、messageboxを使って無理やりできたのですが、おそらくipythonのバージョンの違いの為にその技が効かなくなっています。これは何とかしたいところです。http://stackoverflow.com/questions/27551399/ipython-notebook-open-file-dialog-retrieve-the-full-pathやそのReferenceを見ると、javascriptを使ったもっとスマートな方法(Drag&Dropを含む)も実現可能なようですが、自分で使うにはjavascriptを理解してからにしたいところです。Qtを使う方法も検索すると出てきますが、上記サイトではその問題点を指摘しています。私自身もうまくいっていません。まだtkinterを使う方法の方がましだと思います。ipython notebookの正式なExtensionでできると良いのですがなさそうです。