代码实现
说明:采用thinker库来实现对文件的类型和文件的名字进行操作
"""
做一个桌面应用搜索程序
"""
import tkinter as tk
from tkinter import messagebox, filedialog
import os
root = tk.Tk()
root.title('搜索工具')
root.geometry('600x300')
searchFrame = tk.Frame()
searchFrame.pack()
tk.Label(searchFrame, text='关键字:').pack(side=tk.LEFT, padx=10, pady=10)
searchKey = tk.Entry(searchFrame)
searchKey.pack(side=tk.LEFT, padx=10, pady=10)
tk.Label(searchFrame, text='文件类型:').pack(side=tk.LEFT, padx=10, pady=10)
searchType = tk.Entry(searchFrame)
searchType.pack(side=tk.LEFT, padx=10, pady=10)
searchButton = tk.Button(searchFrame,text='搜索')
searchButton.pack(side=tk.LEFT, padx=10, pady=10)
searchListBox = tk.Listbox(root, width=80)
searchListBox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
searchScrollBar = tk.Scrollbar(root)
searchScrollBar.pack(side=tk.RIGHT, fill=tk.Y)
def search():
fileCounts = []
key = searchKey.get()
fileType = searchType.get()
if not key:
messagebox.showinfo(title='出错了!', message='请输入正确的关键字!')
return
if not fileType:
messagebox.showinfo(title='出错了!', message='请输入正确的文件类型!')
return
if key and fileType:
print('开始执行搜索!')
print('关键字:', key)
print('文件类型:', fileType)
fn = filedialog.askdirectory()
searchListBox.delete(0, tk.END)
for rootPath, dirs, files in os.walk(fn):
for file in files:
if file.endswith(fileType):
if (key in file) and (file.endswith(fileType)):
fileCounts.append(file)
searchListBox.insert(tk.END, rootPath + '\\' + file)
searchListBox.insert(tk.END, '总共搜索到:' + str(len(fileCounts)) + '条!')
searchButton.config(command=search)
searchListBox.config(yscrollcommand=searchScrollBar.set)
searchScrollBar.config(command=searchListBox.yview)
def resultsDisplay (event) :
print('条目被点击了!')
selected = searchListBox.curselection()[0]
selectedFilePath = searchListBox.get(selected)
content = open(selectedFilePath, mode='r', encoding='utf-8').read()
top = tk.Toplevel()
top.title('查看内容')
text = tk.Text(top)
text.pack(side=tk.LEFT, expand=True)
text.insert(tk.END, content)
sb = tk.Scrollbar(top)
sb.pack(side=tk.RIGHT, fill=tk.Y)
sb.config(command=text.yview)
text.config(yscrollcommand=sb.set)
searchListBox.bind('<Double-Button-1>', resultsDisplay)
tk.mainloop()