桌面搜索程序 Python

一个简单的桌面搜索程序。流程化代码:

 1 """
 2     做一个桌面应用搜索程序
 3 """
 4 import tkinter as tk
 5 from tkinter import messagebox, filedialog
 6 import os
 7 
 8 root = tk.Tk()
 9 root.title('搜索程序')
10 root.geometry('600x300')
11 
12 # 布局组件
13 searchFrame = tk.Frame()
14 searchFrame.pack()
15 
16 # 标签1
17 tk.Label(searchFrame, text='关键字:').pack(side=tk.LEFT, padx=10, pady=10)
18 searchKey = tk.Entry(searchFrame)
19 searchKey.pack(side=tk.LEFT, padx=10, pady=10)
20 
21 # 标签2
22 tk.Label(searchFrame, text='文件类型:').pack(side=tk.LEFT, padx=10, pady=10)
23 searchType = tk.Entry(searchFrame)
24 searchType.pack(side=tk.LEFT, padx=10, pady=10)
25 
26 # 标签3
27 searchButton = tk.Button(searchFrame,text='搜索')
28 searchButton.pack(side=tk.LEFT, padx=10, pady=10)
29 
30 # 标签4
31 searchListBox = tk.Listbox(root, width=80)
32 searchListBox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
33 
34 # 标签5
35 searchScrollBar = tk.Scrollbar(root)
36 searchScrollBar.pack(side=tk.RIGHT, fill=tk.Y)
37 
38 def search():
39     fileCounts = []
40     key = searchKey.get()
41     fileType = searchType.get()
42     if not key:
43         messagebox.showinfo(title='出错了!', message='请输入正确的关键字!')
44         return
45     if not fileType:
46         messagebox.showinfo(title='出错了!', message='请输入正确的文件类型!')
47         return
48     if key and fileType:
49         print('开始执行搜索!')
50         fn = filedialog.askdirectory()
51         # 开始遍历选取的文件夹
52         for rootPath, dirs, files in os.walk(fn):
53             # 遍历文件
54             for file in files:
55                 if file.endswith(fileType):
56                 # if (key in file) and (file.endswith(fileType)): # 条件是key
57                     fileCounts.append(file)
58                     searchListBox.insert(tk.END, rootPath + '\\' + file)
59     searchListBox.insert(tk.END, '总共搜索到:' + str(len(fileCounts)) + '条!')
60 
61 searchButton.config(command=search)
62 # 设置滚动条样式
63 searchListBox.config(yscrollcommand=searchScrollBar.set)
64 searchScrollBar.config(command=searchListBox.yview)
65 
66 def resultsDisplay(event):
67     print('条目被点击了!')
68     # 获取当前被选中的条目
69     selected = searchListBox.curselection()[0] # 获取键值
70     # 获取选中文件的路径
71     selectedFilePath = searchListBox.get(selected)
72     # 获取文件内容
73     content = open(selectedFilePath, mode='r', encoding='utf-8').read()
74 
75     # 新建top窗口
76     top = tk.Toplevel()
77     top.title('查看内容')
78     # top.geometry('300x300')
79 
80     # 新建标签
81     text = tk.Text(top) # 布局到top窗口上
82     text.pack(side=tk.LEFT, expand=True)
83     # 将获取到的内容插入到text窗口
84     text.insert(tk.END, content)
85 
86     # 滚动条
87     sb = tk.Scrollbar(top) # 布局到top窗口
88     sb.pack(side=tk.RIGHT, fill=tk.Y)
89     # 设置滚动条的方式
90     sb.config(command=text.yview)
91     text.config(yscrollcommand=sb.set)
92 
93 
94 searchListBox.bind('<Double-Button-1>', resultsDisplay)
95 tk.mainloop()
原文地址:https://www.cnblogs.com/mafu/p/15744762.html