tkinter python 更改列表框文件的名称而不更改该文件的文件目录
tkinter python change a listbox file's name without changing the file directory of that file
我 运行 遇到了这个问题,每当我将文件导入列表框时,列表框中的项目名称就会变成 C:\blahblah\blahblah\test.txt
这很烦人,因为我只想在列表框中显示“测试”或 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()
答案归功于 Henry 的评论,但我已在评论中添加了您的要求。
How to get rid of extensions?
完整的解决方案如下:
from tkinter import *
import os.path
window = Tk()
listbox = Listbox(window)
listbox.pack()
filedirectory = os.listdir("<path>")
for f in filedirectory:
listbox.insert("end", f"{os.path.basename(f).split('.')[0]}")
window.mainloop()
你的问题有一些错别字,我也已经改正了。第一个是 ListBox
应该是 Listbox
第二个是 insert
而不是 inset
.
我 运行 遇到了这个问题,每当我将文件导入列表框时,列表框中的项目名称就会变成 C:\blahblah\blahblah\test.txt 这很烦人,因为我只想在列表框中显示“测试”或 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()
答案归功于 Henry 的评论,但我已在评论中添加了您的要求。
How to get rid of extensions?
完整的解决方案如下:
from tkinter import *
import os.path
window = Tk()
listbox = Listbox(window)
listbox.pack()
filedirectory = os.listdir("<path>")
for f in filedirectory:
listbox.insert("end", f"{os.path.basename(f).split('.')[0]}")
window.mainloop()
你的问题有一些错别字,我也已经改正了。第一个是 ListBox
应该是 Listbox
第二个是 insert
而不是 inset
.