利用tkinter开发文件搜索工具

在这里插入图片描述

运行窗口如上所示,输入关键字和文件类型后,点击搜索按钮,会跳出文件管理器,选择文件夹后,会对选择的文件夹内的文件进行关键字的搜索,然后将包含关键字的文件输出到下面的列表当中,双击可以访问文件内容

import tkinter as tk
from tkinter import messagebox, filedialog
import os

root = tk.Tk()
root.title('文件搜素工具')
root.geometry('600x300')

# 上面一层搜索的组件
search_frame = tk.Frame(root)
search_frame.pack()

tk.Label(search_frame, text='关键字:').pack(side=tk.LEFT, padx=10, pady=10)
key_entry = tk.Entry(search_frame)
key_entry.pack(side=tk.LEFT, padx=10, pady=10)

tk.Label(search_frame, text='文件类型:').pack(side=tk.LEFT, padx=10, pady=10)
type_entry = tk.Entry(search_frame)
type_entry.pack(side=tk.LEFT, padx=10, pady=10)

search_btn = tk.Button(search_frame, text='搜索')
search_btn.pack(side=tk.LEFT, padx=10, pady=10)

list_box = tk.Listbox(root)
list_box.pack(fill=tk.BOTH, expand=True, side=tk.LEFT)


def search():
    # print("按钮被点击了")
    key = key_entry.get()
    file_type = type_entry.get()
    if not key:
        messagebox.showinfo('出错了', '请输入关键字再搜索')
        return
    if not file_type:
        messagebox.showinfo('出错了', '请输入文件类型再搜索')
        return

    # print("关键字:" + key)
    # print("文件类型", file_type)
    # 调用Windows的文件管理系统,获取指定的目录
    fn = filedialog.askdirectory()
    list_box.delete(0, tk.END)  # 搜索前把之前的搜索结果清空
    # print(fn)
    # 目录 目录的子目录 目录的文件
    for root_path, dirs, files in os.walk(fn):
        # print(root_path, dirs, files)
        for file in files:
            file_path = root_path.replace('\\', '/') + './' + file
            if file_path.endswith(file_type):  # 筛选文件类型
                # print(file_path)
                # 筛选关键字
                content = open(file_path, mode='r', encoding='utf-8-sig').read()
                if key in content:
                    list_box.insert(tk.END, file_path)  # tk.END 代表从列表的末尾进行插入


search_btn.config(command=search)

# 添加滚动栏
sb = tk.Scrollbar(root)
sb.pack(side=tk.RIGHT, fill=tk.Y)
# y轴方向滚动会出发滚动条 将sb绑定到list_box
sb.config(command=list_box.yview)
list_box.config(yscrollcommand=sb.set)


# 添加列表元素点击事件
def list_box_click(event):
    # print(event)
    # print("添加列表元素点击事件")
    # 获取点击的内容
    index = list_box.curselection()
    # print(index)
    file_path = list_box.get(index[0])  # 获取到所点击的文件路径
    # print(file_path)
    # 读取被点击的文件内容,显示到新的窗口
    window = tk.Toplevel()  # 子窗口对象
    window.title("文件查看")

    content = open(file_path, mode='r', encoding='utf-8-sig').read()

    text = tk.Text(window)
    text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
    text.insert(tk.END, content)

    # 添加滚动栏
    sb2 = tk.Scrollbar(window)
    sb2.pack(side=tk.RIGHT, fill=tk.Y)
    # y轴方向滚动会出发滚动条 将sb绑定到list_box
    sb2.config(command=text.yview)
    text.config(yscrollcommand=sb2.set)


list_box.bind('<Double-Button-1>', list_box_click)

root.mainloop()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值