1. 程式人生 > 其它 >用python製作檔案搜尋工具,深挖電腦裡的【學習大全】

用python製作檔案搜尋工具,深挖電腦裡的【學習大全】

咳咳~懂得都懂啊

點選此處找管理員小姐姐領取正經資料~

開發環境

  1. 直譯器: Python 3.8.8 | Anaconda, Inc.
  2. 編輯器: pycharm 專業版

先演示效果

開始程式碼,先匯入模組

import tkinter as tk
from tkinter import filedialog
import os

建立視窗

root = tk.Tk()
root.geometry('600x300')
root.title('學習資料搜尋工具')

root.mainloop()

搜尋欄

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():
    print('按鈕被點選了')

button.config(command=search)

1. 獲取關鍵字、檔案型別

key = key_entry.get()
file_type = type_entry.get()
print(key, file_type)

2. 實現搜尋功能

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:
        # 過濾檔案型別,搜尋關鍵字
        if type_entry:  # py 如果輸入了型別,就進行過濾,如果沒有輸入,就不過濾型別
            if file.endswith(file_type):
                # 搜尋關鍵字
                content = open(root_path + '/' + file, mode='r', encoding='utf-8-sig').read()
                if key in content:
                    print(root_path + '/' + file)
                    # 把結果顯示到介面上
                    list_box.insert(tk.END, root_path + '/' + file)

建立滾動視窗並佈局到頁面上

sb = tk.Scrollbar(root)
sb.pack(side=tk.RIGHT, fill=tk.Y)
sb.config(command=list_box.yview)
list_box.config(yscrollcommand=sb.set)

觸發繫結事件

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

1. 獲取到選中的內容

def list_click(event):
    print('列表框元件的內容被點選了')
    index = list_box.curselection()[0]
    path = list_box.get(index)
    print(path)

2. 讀取選中路徑的內容

content = open(path, mode='r', encoding='utf-8').read()
print(content)

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)

兄弟們,這不得點一波收藏+關注?