如何在Tkinter窗口中显示已选文件路径(替代控制台输出)
解决方案
要在Tkinter窗口内显示选中的文件路径,你可以新增两个Label组件专门用于展示路径,然后在选择文件的函数中更新这些标签的内容。以下是修改后的完整代码:
from tkinter import Tk, Label, Button from tkinter.filedialog import askopenfile ws = Tk() ws.title('Uploading Files') ws.geometry('600x200') # 加宽窗口,给路径显示留出空间 # 全局变量存储文件内容 file1 = "" file2 = "" def open_file1(): file_path = askopenfile(mode='r', filetypes=[('TPI Files', '*.tpi')]) if file_path is not None: global file1 file1 = file_path.read() # 更新标签显示文件路径 file1_path_label.config(text=file_path.name) else: # 用户取消选择时清空标签 file1_path_label.config(text="") def open_file2(): file_path = askopenfile(mode='r', filetypes=[('TPI Files', '*.tpi')]) if file_path is not None: global file2 file2 = file_path.read() # 更新标签显示文件路径 file2_path_label.config(text=file_path.name) else: # 用户取消选择时清空标签 file2_path_label.config(text="") def uploadFiles(data=None): global content, content2 content = file1 content2 = file2 ws.destroy() # 旧文件选择区域 first = Label(ws, text='Upload old File ') first.grid(row=0, column=0, padx=10, pady=5) firstbtn = Button(ws, text='Choose File', command=open_file1) firstbtn.grid(row=0, column=1, padx=5, pady=5) # 新增:显示旧文件路径的标签 file1_path_label = Label(ws, text="", fg="blue") file1_path_label.grid(row=0, column=2, padx=10, pady=5, sticky="w") # 新文件选择区域 second = Label(ws, text='Upload new File ') second.grid(row=1, column=0, padx=10, pady=5) secondbtn = Button(ws, text='Choose File ', command=open_file2) secondbtn.grid(row=1, column=1, padx=5, pady=5) # 新增:显示新文件路径的标签 file2_path_label = Label(ws, text="", fg="blue") file2_path_label.grid(row=1, column=2, padx=10, pady=5, sticky="w") upld = Button(ws, text='Upload Files', command=uploadFiles) upld.grid(row=3, columnspan=3, pady=20) ws.mainloop()
关键修改说明
- 新增了
file1_path_label和file2_path_label两个标签,用于展示选中的文件路径,设置为蓝色文字便于区分,使用sticky="w"让路径左对齐显示。 - 加宽了窗口尺寸(从400px改为600px),避免长路径被截断。
- 在
open_file1和open_file2函数中,当成功选中文件时,通过config(text=file_path.name)更新对应标签的内容;若用户取消文件选择,则清空标签内容。 - 修正了原代码中
filetypes的描述(从"All Files"改为"TPI Files"更准确),并初始化了全局变量file1和file2为空字符串,避免未选择文件时出现报错。
内容的提问来源于stack exchange,提问作者gcoder
相关产品推荐
相关产品推荐

