2017-03-16 15 views
-1

ファイルを検索するための参照ボタンがあり、選択したファイルを開くプログラムを作成しています。私はあなたが 'askopenfile'を使うことができると知っていますが、最初に名前を取得したかったので、tkinterウィンドウのEntryボックスに表示され、ユーザは 'Use this file'を押して開きます。askopenfilenameを使ってテキストファイルの内容を表示して場所を取得する方法

from tkinter import * 
from tkinter import ttk 
from tkinter import filedialog 

def main(): 
    self = Tk() 

    F1 = LabelFrame(self, text="Select File") 
    F1.grid(row=0, column=0, padx=3) 

    browse = Button(F1, text="Browse...", command=openfile) 
    browse.grid(row=0, column=2, padx=1, pady=3) 

    E1 = Entry(F1, text="") 
    E1.grid(row=0, column=1, sticky="ew") 

    L1 = Label(F1, text="Filename:") 
    L1.grid(row=0, column=0, padx=3) 

    B1 = Button(F1, text="Use This File", command=go) 
    B1.grid(row=1, column=2, padx=3, pady=3) 

    B2 = Button(F1, text="Cancel", width=7) 
    B2.grid(row=1, column=1, sticky="e") 

    self.mainloop() 

def openfile(): 
    global filename 
    filename = filedialog.askopenfilename() 
    E1.delete(0, END) 
    E1.insert(0, filename) 

def go(): 
    global filename 
    file = open(filename) 
    file.read() 
    print(file) 
    file.close() 
main() 

だから、テキストファイルを選択し、[参照]を押して、Tkinterのウィンドウを作り、パスがエントリに書き込まれ、その後、私はB1を押すと、ファイルを開き、内容を印刷するプログラムを取得したいですしかし、それだけで印刷します:あなたは、変数や印刷、ファイルではなくオブジェクトにread()から返された値を保存する必要が

<_io.TextIOWrapper name='C:/Users/Me/text.txt' mode='r' encoding='cp1252'> 

答えて

2

file_content = file.read() 
print(file_content) 
+0

ありがとうございます – olymposeical

関連する問題