首页 > 解决方案 > 按钮上的应用程序名称

问题描述

是否可以让文件名出现而不是路径,而且我没有损坏json路径?例如:C:users/desktop/book.txt。我想让它只显示名称,例如 book,txt。名称,即 file_name 变量显示在按钮上。

代码完全正常工作。

我的代码:

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

            btn1.config(text=file_name)
    else:
        os.startfile(file_name)

        with open("Filen.json", "w") as file1:
            json.dump([file_name], file1, indent=2, ensure_ascii=False)


load_json()
btn1 =  tk.Button(window, text=file_name, command=openu)
btn1.place(x = 20, y = 25)

标签: pythonjsontkinter

解决方案


如果您有如下路径,您可以轻松提取文件名。

import os
file_name = os.path.basename(your_path)

如果您有路径 C:users/desktop/book.txt,那么您将获得如下所示的文件名。

file_name=os.path.basename('C:users/desktop/book.txt')

推荐阅读