有没有可能让文件名出现而不是路径,而且我没有损坏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)
如果您有如下路径,则可以轻松提取文件名。
import os
file_name = os.path.basename(your_path)
如果你有一个路径 C:users/desktop/book.txt 那么你会得到如下所示的文件名。
file_name=os.path.basename('C:users/desktop/book.txt')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句