tk filedialogで開いて、選択したファイルの内容を読みたいと思います。ファイルを選択して「開く」ボタンをクリックすると、ファイルは開きませんが、ダイアログボックスは閉じます。選択したファイルをメモ帳で開くと、ファイル内のコンテンツを読み取ることができます。 @PM 2RINGと@Erikからヒントを使用してtkfiledialogでファイルを開き、メモ帳でコンテンツを読む方法
from tkinter import *
from tkinter import filedialog
def my_file():
filename = filedialog.askopenfile(mode="r", initialdir="/", title="select file",
filetypes=(("text files", "*.txt"), ("all files", "*.*")))
root = Tk()
root.geometry("300x300")
#open the selected txt file with notepad to read the content
b = Button(root, text="open text file", command = my_file).pack()
root.mainloop()
EDIT 私は、ファイルを選択したときにnotepad.exeをして開くためにそれを返すためにfiledialog.askopenfilenameするfiledialog.askopenfileを変更しました。
from tkinter import *
from tkinter import filedialog
import os
def my_file():
filename = filedialog.askopenfilename(initialdir="C:/", title="select
file", filetypes=(("text files", "*.txt"), ("all files", "*.*")))
for f in filename:
return f
os.system(r"C:/notepad.exe" + f)
root = Tk()
root.geometry("300x300")
#open the selected txt file with notepad to read
the content
b = Button(root, text="open text file", command = my_file).pack()
root.mainloop()
その出力このエラー: これはコードです
Blockquote'C:/notepad.exet' is not recognized as an internal or external command, operable program or batch file. Blockquote
が、私はそれがterminal.Iにディレクトリを印刷する印刷するリターンを変更したときにサブプロセスを開こうとした
subprocess.Popen([r'C:\Program Files (x86)\Notepad.exe' + f])
また、これで開くこともありません。
メモ帳でファイルを読みたい場合は、メモ帳で開いてみてください。 'filedialog.askopenfile'はTkinterプログラムの中でそれらを使うことができるようにファイルを開くためのものです。例えばTextウィジェットの中にテキストを表示します。私はメモ帳でファイルを開くには、関連する 'filedialog.askopenfilename'と' subprocess'モジュール関数または 'os.system'を使うことができますが、それはちょっと奇妙なIMHOでしょう。 –