构建一个接口,根据用户输入搜索.text文件,然后在其旁边打印结果

时间:2013-05-22 11:34:33

标签: python user-interface text python-2.7 tkinter

我一直在玩这个,我觉得我弄得一团糟。 我需要一个界面,如果有人在文本字段中输入一个单词,它将在.txt文件中打印包含该单词旁边框中的任何行。 这是我到目前为止所做的:

    import Tkinter as tk
    from Tkinter import *
    from scipy import *

    import math

    def cbc(id, tex):
        return lambda : callback(id, tex)

    def callback(id, tex):                                 
        t = Search(id)
        tex.insert(tk.END, t)
        tex.see(tk.END)
    #def retrieve_input():
    #    input = self.entn.get("0.0",END)
    def Search(id):
        with open("file.txt", "r") as s:
            searchlines = s.readlines()
        for i, line in enumerate(searchlines):             
            if entn.get() in line: 
                for line in searchlines[i:i+1]: print line,    
                print
    top = tk.Tk()
    tex = tk.Text(master=top)                              
    tex.pack(side=tk.RIGHT)                                
    bop = tk.Frame()
    bop.pack(side=tk.LEFT)                                 
    entn = tk.Entry()
    entn.pack(side=tk.TOP, fill=Y)                         
    tb = "Search"
    b = tk.Button(bop, text=tb, command=cbc(id, tex))   
    b.pack()

    tk.Button(bop, text='Exit', command=top.destroy).pack() 
    top.mainloop()

我对此很陌生,你可能会说 - 所以任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:0)

你的回调是插入Search(id)的结果,但该函数没有返回任何内容。您需要在该函数中添加一个return语句,以返回要在文本小部件中显示的字符串。

更好的方法是将对文本小部件的引用传递给Search,以便您可以在找到它们时直接插入每个匹配项。