You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter开发:如何让按钮显示文件名而非完整路径且不破坏JSON存储路径

你只需要在给按钮设置显示文本时调用os.path.basename()方法从完整路径中提取纯文件名即可,文件路径存储、调用的逻辑完全不需要修改,不会影响原有功能。

具体修改点

  • 选中文件后更新按钮文本时,把原来的完整路径替换为提取出的文件名
  • 初始化按钮时,如果有历史存储的文件路径,也用同样规则生成按钮显示文本
  • 顺带优化了存储逻辑:原来的逻辑需要打开一次文件才会把路径写入JSON,调整为选中文件后立刻写入,避免程序异常退出时丢失选中的路径

修改后完整代码

import tkinter as tk
import tkinter.filedialog as tfd
import json
import os

window = tk.Tk()
window.title("Open")
window.geometry("600x400")
window.resizable(False, False)

file_name = ""


def load_json():
    global file_name
    if os.path.exists("Filen.json"):
        with open("Filen.json") as file1:
            contents = json.load(file1)
            if len(contents) > 0:
                if contents[0] != "":
                    file_name = contents[0]
    else:
        with open("Filen.json", "w") as file1:
            json.dump([file_name], file1, indent=2, ensure_ascii=False)

def openu():
    global file_name
    load_json()
    if file_name == "":
        path = tfd.askopenfilename()
        if path:
            file_name = path
            # 仅按钮显示文件名,完整路径保留在file_name变量中
            btn1.config(text=os.path.basename(file_name))
            # 选中文件后立即写入JSON
            with open("Filen.json", "w") as file1:
                json.dump([file_name], file1, indent=2, ensure_ascii=False)
    else:
        os.startfile(file_name)


load_json()
# 初始化按钮时做兼容处理,无历史路径则显示提示文本
init_btn_text = os.path.basename(file_name) if file_name else "选择文件"
btn1 =  tk.Button(window, text=init_btn_text, command=openu)
btn1.place(x = 20, y = 25)

window.mainloop()

内容的提问来源于stack exchange,提问作者FiolDoll

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 04:24:02