【发布时间】:2021-09-30 07:58:54
【问题描述】:
我遇到了这个问题,每当我将文件导入我的列表框时,它都会在列表框中创建项目的名称 C:\blahblah\blahblah\test.txt 这很烦人,因为我只希望“test”或 test.txt 显示在列表框中,但仍然不干扰文件目录,这可能吗?
我正在使用 from tkinter import * btw
我没有尝试太多,因为一旦我更改文件名,文件目录就会随之而来。
示例:
window = Tk()
list = []
listbox = ListBox(window)
listbox.pack()
filedirectory = os.listdir("blahblah/")
for f in filedirectory:
listbox.inset("end", f"blahblah/{f}") #where it says blahblah is an example of where you could "potentially" change the name but that changes the file directory with it
window.mainloop()
【问题讨论】:
-
你能分享一下你累了什么(你的代码)吗?如果不查看您的代码,我也无法给您任何建议。
-
在 for 循环中使用
import os.path,然后使用os.path.basename(f)。您的示例中还有一个错字。listbox.inset应该是listbox.insert。 -
如果文本文件和python文件在同一目录下,那么你可以简单地使用
test.txt而不是提供完整路径 -
是的,但是作为一个可执行文件,如果有 30 个文件和 exe 文件看起来很奇怪,但是确实可以。
标签: python file tkinter filepath