-1
我正在編寫一個程序,它只有一個瀏覽按鈕來搜索文件,然後打開您選擇的文件。我知道你可以使用'askopenfile',但是我想先取得名字,這樣它可以顯示在我的tkinter窗口的輸入框中,然後用戶按下'使用這個文件',然後它會打開。如何在使用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,並獲得該程序打開文件和打印內容,但它只是打印:
<_io.TextIOWrapper name='C:/Users/Me/text.txt' mode='r' encoding='cp1252'>
感謝它現在的工作 – olymposeical