运行窗口如上所示,输入关键字和文件类型后,点击搜索按钮,会跳出文件管理器,选择文件夹后,会对选择的文件夹内的文件进行关键字的搜索,然后将包含关键字的文件输出到下面的列表当中,双击可以访问文件内容
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99import 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()
最后
以上就是曾经蚂蚁最近收集整理的关于利用tkinter开发文件搜索工具的全部内容,更多相关利用tkinter开发文件搜索工具内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复