python的tkinter的选择文件并显示在CTkEntry

import customtkinter as ctk
from tkinter import filedialog


class MySelectFileFrameGui:
def __init__(self, main_frame: ctk.CTkFrame):
# 定义返回的文件路径
self.file_path = None

# 定义主窗口
self.main_frame = main_frame

# 定义部件主窗口
self.select_file_main_frame = ctk.CTkFrame(
master=self.main_frame,
corner_radius=0,
)
self.select_file_main_frame.grid(row=0, column=0, sticky="nsew")
self.select_file_main_frame.grid_columnconfigure(index=0, weight=1)

# 定义选择文件路径展示对话框
self.file_path_entry = ctk.CTkEntry(
master=self.select_file_main_frame,
placeholder_text="文件路径",
state="disabled",
)
self.file_path_entry.grid(row=0, column=0, padx=(20, 10), pady=(20, 20), sticky="nsew")

# 定义选择文件按钮
self.select_file_button = ctk.CTkButton(
master=self.select_file_main_frame,
height=40,
text="选择文件",
command=self.set_select_file_button_event,
)
self.select_file_button.grid(row=0, column=1, padx=(10, 20), pady=(20, 20), sticky="nsew")

# 选择文件按钮事件
def set_select_file_button_event(self):
file_path = filedialog.askopenfilename(
title="Select a File",
filetypes=(("Excel files", "*.xls"), ("Excel files", "*.xlsx"))
)
if file_path:
self.file_path_entry.configure(state="normal") # 先设置为正常状态以便更新文本
self.file_path_entry.delete(0, ctk.END) # 删除现有文本
self.file_path_entry.insert(0, file_path) # 插入新文本
self.file_path_entry.configure(state="disabled") # 设置为不可编辑状态

# 返回选择文件面板
def set_select_file_main_panel(self):
return self.select_file_main_frame

# 返回文件路径
def get_excel_file_path(self):
return self.file_path_entry.get()


# # 创建主窗口
# root = ctk.CTk()
# root.title("File Selector")
# root.geometry(f"{1100}x{580}")
# root.grid_columnconfigure(0, weight=1)
#
# mfpg = MySelectFileFrameGui(main_frame=root)
# mfpg.set_select_file_main_panel()
#
# # 运行主循环
# root.mainloop()
posted @ 2024-07-24 09:32  煦色韶光  阅读(5)  评论(0编辑  收藏  举报