如何使用askopenfile获取有效的filenam

2024-04-19 11:06:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Tkinter和tkFileDialog创建一个程序,它打开一个文件进行读取,然后将其打包到一个文本小部件中,但是,每当我运行此程序时:

from Tkinter import *
from tkFileDialog import askopenfile
import time
m = Tk()

def filefind():
   file = askopenfile()
   f = open(str(file), "r+")
   x = f.read()
   t = Text(m)
   t.insert(INSERT, x)
   t.pack()


b = Button(m, text='File Picker', command=filefind)
b.pack()
m.mainloop()

我明白了:

^{pr2}$

Tags: 文件from文本import程序time部件tkinter
1条回答
网友
1楼 · 发布于 2024-04-19 11:06:46

问题是;askopenfile()返回的是一个对象,而不仅仅是名称。如果您打印file,您将得到<_io.TextIOWrapper name='/File/Path/To/File.txt' mode='r' encoding='UTF-8'>。您需要来自对象的name=。要得到这个结果,您只需将f = open(str(file), "r+")替换为f = open(file.name, "r+")。在

下面是它在代码中的外观:

from Tkinter import *
from tkFileDialog import askopenfile
import time
m = Tk()

def filefind():
    file = askopenfile()
    f = open(file.name, "r+")  # This will fix the issue.
    x = f.read()
    t = Text(m)
    t.insert(INSERT, x)
    t.pack()


b = Button(m, text='File Picker', command=filefind)
b.pack()
m.mainloop()

编辑

一种更简洁的方法是让askopenfile()执行打开文件的工作,而不是用open()再次“重新打开”它。下面是更干净的版本:

^{pr2}$

相关问题 更多 >