我正在尝试在Tkinter中实现浏览功能,我可以实现浏览文件选项,但是,在选择了在控制台上显示文件位置的文件之后,如何在标签上打印该位置呢?在下面的位置,应该打印file_location或file_name。
entry_1.insert(0,'File_location')
例如,文件位置是
文件名为
C:\Users\Desktop\test\test.txt的路径
因此,这个文件位置应该打印在标签上,而不是控制台上。
同时,如果我只想要一个没有文件名的路径,那么它是如何实现的呢?
没有文件名的
路径。C:\用户\桌面\测试
为了实现这个特性,我需要添加哪些额外的功能?任何帮助都将不胜感激。
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from io import StringIO
import sys
import os
root = Tk()
root.geometry('700x650')
root.title("Data Form")
def file_opener():
input = filedialog.askopenfiles(initialdir="/")
print(input)
for i in input:
print(i)
label_1 = Label(root, text="Location",width=20,font=("bold", 10))
label_1.place(x=65,y=130)
x= Button(root, text='Browse',command=file_opener,width=6,bg='gray',fg='white')
x.place(x=575,y=130)
entry_1 = Entry(root)
entry_1.place(x=240,y=130,height=20, width=300)
entry_1.insert(0, 'File_location')
root.mainloop()
发布于 2021-03-10 03:40:32
而不是使用
filedialog.askopenfile(initialdir="/")
使用
filedialog.askopenfilename(initialdir="/")
如果要选择多个文件并获得一个元组作为输入,请使用
filedialog.askopenfilenames(initialdir="/")
对于没有文件名的路径,请使用以下命令
import os
os.path.dirname(input)
可以通过以下方式将文本插入到条目中
更新:
entry_1.delete(0, END)
entry_1.insert(0, input[0])
全修改代码(更新:)
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from io import StringIO
import sys
import os
root = Tk()
root.geometry('700x650')
root.title("Data Form")
def file_opener():
# input = filedialog.askopenfilenames(initialdir="/") # for selecting multiple files
input = filedialog.askopenfilename(initialdir="/")
entry_1.delete(0, END)
entry_1.insert(0, input)
label_1 = Label(root, text="Location", width=20, font=("bold", 10))
label_1.place(x=65, y=130)
x = Button(root, text='Browse', command=file_opener, width=6, bg='gray', fg='white')
x.place(x=575, y=130)
entry_1 = Entry(root)
entry_1.place(x=240, y=130, height=20, width=300)
entry_1.insert(0, 'File_location')
root.mainloop()
https://stackoverflow.com/questions/66562046
复制相似问题