import os
import tkinter as tk
from tkinter import filedialog
class FileExplorer:
def __init__(self, root):
self.current_path = os.getcwd()
self.root = root
self.root.title("File Explorer")
# 创建文件列表框
self.listbox = tk.Listbox(self.root, width=80)
self.listbox.pack(side="top", fill="both", expand=True)
# 添加滚动条
scrollbar = tk.Scrollbar(self.listbox)
scrollbar.pack(side="right", fill="y")
# 设置文件列表框和滚动条的关联
self.listbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=self.listbox.yview)
# 创建菜单栏
menu_bar = tk.Menu(self.root)
self.root.config(menu=menu_bar)
# 创建菜单
file_menu = tk.Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="Open", command=self.open_file)
file_menu.add_command(label="Exit", command=self.exit)
# 显示当前路径
self.show_dir_content(self.current_path)
# 打开文件
def open_file(self):
file_path = filedialog.askopenfilename(initialdir=self.current_path, title="Select file")
if file_path:
os.startfile(file_path)
# 显示目录内容
def show_dir_content(self, path):
self.current_path = path
self.listbox.delete(0, tk.END)
self.listbox.insert(tk.END, "..") # 上级目录
for f in os.listdir(path):
self.listbox.insert(tk.END, f)
# 列表框双击事件
def on_double_click(self, event):
selection = self.listbox.curselection()
if selection:
item = self.listbox.get(selection[0])
path = os.path.join(self.current_path, item)
if os.path.isdir(path):
self.show_dir_content(path)
# 退出程序
def exit(self):
self.root.destroy()
# 启动程序
if __name__ == '__main__':
root = tk.Tk()
FileExplorer(root)
root.bind("<Double-Button-1>", FileExplorer(root).on_double_click)
root.mainloop()
用python写扫雷tk
猜你喜欢
转载自blog.csdn.net/yydsdeni/article/details/132642593
今日推荐
周排行