#!/usr/bin/env python
# -*- coding:utf-8 -*-
from Tkinter import *
import tkMessageBox
import tkFileDialog
import os
import fnmatch
from ScrolledText import ScrolledText
def func():
str1 = ent1.get()
str2 = ent2.get()
if not (str1 and str2): #not str1 or not str2 ,当前两个值都不可以为空。
tkMessageBox.showinfo('温馨提示','请先输入查询的关键字和文件类型再选择文件夹!')
return
fn = tkFileDialog.askdirectory() #选择一个文件夹路径
if not fn:
return
listbox.delete(0,END)
fnlist = os.walk(fn)
for root,dirs,files in fnlist:
for i in fnmatch.filter(files,str2): #过滤,指定文件类型。
f = open(root + "/" + i).read()
if str1 in f:
listbox.insert(END,root + "/" + i)
def func2(e):
if not listbox.curselection():
return
window = Tk()
window.title("文件查看")
text = ScrolledText(window,width=100) #带滚动条的多行文本框
text.grid()
path = listbox.get(listbox.curselection(),last=None)
fn = open(path)
text.insert(END,fn.read())
fn.close()
root = Tk()
root.title("文件搜索工具")
root.geometry("+600+300")
Label(root,text="搜索词").grid()
ent1 = Entry(root)
ent1.grid(row=0,column=1) #row=横坐标,column=纵坐标
Label(root,text="文件类型").grid(row=0,column=2)
ent2 = Entry(root)
ent2.grid(row=0,column=3)
btn = Button(root,text="选择文件",command=func)
btn.grid(row=0,column=4)
var1 = StringVar()
listbox = Listbox(root,width=80)
listbox.bind("<Double-Button-1>",func2)
listbox.grid(row=1,column=0,columnspan=5)
#grid=网格布局
root.mainloop()
转载于:https://blog.51cto.com/liyuanjie/1967410