表达式“ value.get()”返回相同值的倍数

时间:2018-10-30 20:05:21

标签: python python-3.x file

对于波纹管代码,在findspec命令上,我尝试仅返回用户键入的文件路径和目录名称。如果不存在文件,则显示“找不到文件”。

这是不起作用的部分:

def findspec():
    r1 = tar.get()
    rootdir = '.'
    for dirname, subdirlist, filelist in os.walk(rootdir, topdown=False):
        for file in filelist:
            if fnmatch.fnmatch(file, tar.get()):
                list1.insert(END, dirname + "--->" + str(r1))
            else:
                list1.insert(END, "File not found")

它应该返回此:

User/%User%/directory ---> config.py
User/%User%/directory/static ---> config.py

相反,它返回以下内容:

File not FOund
File not Found
File not Found
File not Found
File not Found
File not Found
File not Found
File not Found
File not Found
File not Found
File not Found
User/%User%/directory ---> config.py
File not Found
File not Found
User/%User%/directory/static ---> config.py
File not Found
File not Found
File not Found
File not Found
File not Found
File not Found
File not Found

源代码如下:

import os
import fnmatch
import tkinter
from tkinter import *
from difflib import get_close_matches

def searchdir():
    rootdir = '.'
    for dirname, subdirlist, filelist in os.walk(rootdir, topdown=False):
        for fname in filelist:
            list1.insert(END, dirname +  '\t%s' % fname)

def findspec():
    r1 = tar.get()
    rootdir = '.'
    for dirname, subdirlist, filelist in os.walk(rootdir, topdown=False):
        for file in filelist:
            if fnmatch.fnmatch(file, tar.get()):
                list1.insert(END, dirname + "--->" + str(r1))
            else:
                list1.insert(END, "File not found")

w=Tk()

b1 = Button(w, text="Search", command=findspec)
b1.grid(row=0, column=0, columnspan=2)

tar=StringVar()
e1 = Entry(w, textvariable=tar)
e1.grid(row=0, column=1, columnspan=4)

b2 = Button(w, text="Start", command=searchdir)
b2.grid(row=1, column=0, columnspan=2)

#listbox
list1=Listbox(w, height=17, width=75, selectmode=EXTENDED)
list1.grid(row=2, column=0, rowspan=7, columnspan=4, sticky=(N, S, E), pady=5, padx=5)

sb1=Scrollbar(w)
sb1.grid(row=2, column=4, rowspan=7, sticky='nsw', pady=5)
list1.configure(yscrollcommand=sb1.set)
sb1.configure(command=list1.yview)

sb2=Scrollbar(w, orient=HORIZONTAL)
sb2.grid(row=10, column=0, columnspan=4, sticky='esw', padx=5)
list1.configure(xscrollcommand=sb2.set)
sb2.configure(command=list1.xview)

list1.bind('<<ListboxSelect>>')

if __name__=='__main__':
    w.mainloop()

我做错什么了吗?我只是在想什么吗? 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

for file in filelist:将对if/else中的每个文件执行filelist检查。但是似乎您不希望不是每次else都失败时才执行fnmatch.fnmatch()子句,而是仅当搜索用尽并且没有将结果添加到列表时才执行len(filelist) < 1

if fnmatch.fnmatch(file, r1):
    list1.insert(END, dirname + "--->" + str(r1))
elif list1.size() < 1:
    list1.insert(END, "File not found")