构建一个界面,根据用户输入搜索一个.txt文件,然后在i旁边打印结果

2024-10-02 22:33:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在玩这个,我觉得我把它弄得一团糟。 我需要一个界面,如果有人在文本字段中输入一个单词,它将打印包含该单词的.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()

我是新来的,你可能知道-所以任何帮助都会非常感激。你知道吗


Tags: inimportidsearchtopdeflineside
1条回答
网友
1楼 · 发布于 2024-10-02 22:33:36

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

更好的方法可能是将对文本小部件的引用传递给Search,这样就可以在找到匹配项时直接插入它们。你知道吗

相关问题 更多 >