python - 按钮上的应用程序名称
问题描述
是否可以让文件名出现而不是路径,而且我没有损坏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')
推荐阅读
- azure-devops - 在流程模板中使用 Reviewed By 字段的安全性
- excel - 如何根据其旁边的单元格中的值更改来修改单元格值
- java - 如何在java常量中传递jenkins参数值
- java - 如果消费者线程面临异常,如何停止生产者线程
- python - Python (Pytorch) - 循环和日志记录
- reactjs - Next.js 在下一页的 getInitialProps 完成加载时保持当前页面处于活动状态并重新渲染
- java - 弹簧一对一的关系
- azure - 新 Microsoft.Azure.Cosmos SDK 中的 CompositeToken
- ruby-on-rails - 如何在用户登录前允许查看指定资源?
- postgresql - 使用 PostgresSQL 动态转置表