GUI--tkinter简单电脑文件搜索工具

GUI–tkinter简单电脑文件搜索工具

tkinter可以做很多小玩意的程序,下面就介绍一个用tkinter做的简单的文件搜索工具。

先展示该应用程序的界面:

在这里插入图片描述

1. 模块导入

需要导入的模块有 os,tkinter

os 和tkinter都是是 python 标准库模块,python自带,无需单独安装。

os顾名思义就是与操作系统相关的库,tkinter创建GUI应用程序。

import os
import tkinter as tk
from tkinter import filedialog  # Tkinter 文件对话框filedialog模块
# 主要用到:filedialog.askdirectory():生成打开目录的对话框

2.设计界面

由上图可以看出,界面分上下两部分。

上面那部分有两个输入框,可以用来限制搜索范围,外加一个搜索按钮,所以页面很明显的是由两个label组件和两个entry组件,加一个button组件构成上半部分。

而下面那部分则是由一个Listbox组件构成,展现出搜索到的内容,右侧还布置了一个scrollbar滚动窗口,方便界面内容过多时,可以上下拉动。

上半部分搜索框界面主要代码:

"""搜索框"""
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)
button = tk.Button(search_frame, text='搜索')
button.pack(side=tk.LEFT, padx=10, pady=10)

下半部分展示框界面主要代码

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

# 创建滚动窗口并布局到页面上
sb = tk.Scrollbar(root)
sb.pack(side=tk.RIGHT, fill=tk.Y)
sb.config(command=list_box.yview)
list_box.config(yscrollcommand=sb.set)

3.实现搜索功能

思路:

  1. 获取关键字、和文件类型

    通过.get()方法可以获取Entry组件中用户输入的内容。

    key = key_entry.get()
    file_type = type_entry.get()
    
  2. 读取Windows系统文件

    通过Tkinter中的文件对话框filedialog模块,生成一个打开目录的对话框,以便于读取Windows系统文件

    dir_path = filedialog.askdirectory()
    
  3. 实现搜索功能

    通过os中的walk内置函数递归遍历对应的文件夹

    返回的结果是3个元组依次:dirpath,dirnames,filenames
    dirpath:文件所在的路径
    dirnames:子目录名称
    filenames: 文件名称(不包含路径)

    接着用for循环得到用户选择文件目录下的每个文件名,文件路径,

    其次就要先过滤掉文件类型,再来进行关键字搜索

    endswith() 方法就用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。

    open().read()打开并读取每一个文件的内容,判断是否含有关键词。

    file_list = os.walk(dir_path)
    for root_path, dirs, files in file_list:
        # 目录路径, 目录下的子目录, 目录下的文件
        for file in files:
            # 过滤文件类型,搜索关键字
            try:
                if type_entry:
                    # 如果输入了类型,就进行过滤,如果没有输入,就不过滤类型
                    if file.endswith(file_type):
                        # 搜索关键字
                        content = open(root_path + '/' + file, mode='r', encoding='utf-8').read()
                        if key in content:
                            print(root_path + '/' + file)
                            # 4. 将搜索到的结果显示到界面
                            list_box.insert(tk.END, root_path + '/' + file)
            except Exception as e:
                 print(e)
    
  4. 将搜索到的结果显示到界面

    通过list_box.insert()方法就可以把搜索到的结果显示在Listbox组件中

    list_box.insert(tk.END, root_path + '/' + file)
    

其中有的文件可能奇奇怪怪,open打不开,就会报错,程序被迫停止运行,就加上一个异常捕获。

完善了搜索功能,接着就要把搜索函数绑定到button组件中button.config(command=search)

当Listbox组件页面中,显示出搜索到的结果时,我们可以点击该搜索结果,以此来打开该文件,查看文件里是否有我们输入的关键词信息。

实现该功能分为3步:

  1. 获取到选中的内容

    主要用到listbox中的.get()返回指定索引的选项值,和.curselection()返回当前选中项的索引两个方法

    index = list_box.curselection()[0]
    path = list_box.get(index)
    
  2. 读取选中的路径内容

    同上用open().read()方法读取

    content = open(path, mode='r', encoding='utf-8').read()
    
  3. 将内容显示到新的窗口

    用到tkinter中的Toplevel组件打开一个新窗口,接着在新窗口里添加一个Text组件来显示选中内容。

    top = tk.Toplevel(root)
    filename = path.split('/')[-1]
    top.title(filename)
    text = tk.Text(top)
    text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
    text.insert(tk.END, content)
    
  4. 绑定双击事件

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

完整代码:

import os
import tkinter as tk
from tkinter import filedialog

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

"""搜索框"""
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)
button = tk.Button(search_frame, text='搜索')
button.pack(side=tk.LEFT, padx=10, pady=10)

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

# 点击按钮搜索文件
def search():
    # 1. 获取关键字、文件类型
    key = key_entry.get()
    file_type = type_entry.get()
    print(key, file_type)

    # 2. 读取windows 系统的文件
    dir_path = filedialog.askdirectory()
    # print(dir_path)   # 遍历文件,实现搜索功能
    file_list = os.walk(dir_path)
    for root_path, dirs, files in file_list:
        # 目录路径, 目录下的子目录, 目录下的文件
        # print(root_path, dirs, files)
        for file in files:
            # 过滤文件类型,搜索关键字
            try:
                if type_entry:
                    # 如果输入了类型,就进行过滤,如果没有输入,就不过滤类型
                    if file.endswith(file_type):
                        # 搜索关键字
                        # print(root_path + '/' + file)
                        content = open(root_path + '/' + file, mode='r', encoding='utf-8').read()
                        if key in content:
                            print(root_path + '/' + file)
                            list_box.insert(tk.END, root_path + '/' + file)
            except Exception as e:
                print(e)
    # 3. 实现搜索功能
    # 4. 将搜索到的结果显示到界面


# 创建滚动窗口并布局到页面上
sb = tk.Scrollbar(root)
sb.pack(side=tk.RIGHT, fill=tk.Y)
sb.config(command=list_box.yview)
list_box.config(yscrollcommand=sb.set)

button.config(command=search)

def list_click(event):
    # 1. 获取到选中的内容
    index = list_box.curselection()[0]
    path = list_box.get(index)
    print(path)
    # 2. 读取选中的路径内容
    content = open(path, mode='r', encoding='utf-8').read()
    # 3. 将内容显示到新的窗口
    top = tk.Toplevel(root)
    filename = path.split('/')[-1]
    top.title(filename)
    text = tk.Text(top)
    text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
    text.insert(tk.END, content)


# 绑定点击事件
list_box.bind('<Double-Button-1>', list_click)

root.mainloop()

完整效果展示:

在这里插入图片描述
谢谢阅读,点赞,加收藏!!!
也欢迎评论,一起学习!!!

  • 2
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

皮卡搭皮卡丘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值