-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