【问题标题】:How can I put user input inside text widget and do search in Log file with tkinter using Python如何将用户输入放在文本小部件中,并使用 Python 使用 tkinter 在日志文件中进行搜索
【发布时间】:2020-10-25 02:11:01
【问题描述】:

尝试编写用于在日志文件myFileMonitor.log 中搜索单词的代码。搜索部分工作正常,但我希望用户输入的搜索显示在tkinter 的文本小部件内。每当我运行程序时,用户输入都会在pycharm 中进入终端模式,并且在输入要搜索的单词后,搜索结果会显示在文本小部件中(如屏幕截图)。如何将用户输入嵌入到文本小部件中? python新手。

当前结果:

我的代码:

from tkinter import *

class MAIN:
    def __init__(self):
        self.watchdog = None
        self.watch_path = '.'
        self.root = Tk()
        self.messagebox = Text(width=100, height=30)
        self.root.title("KIDS")
        self.messagebox.pack()

        # Configure menu
        my_menu = Menu(self.root)
        self.root.config(menu=my_menu)

        # Create 'Report' menu items
        report_menu = Menu(my_menu, tearoff=0)
        my_menu.add_cascade(label="Report & Search", menu=report_menu)
        report_menu.add_separator()
        report_menu.add_command(label="Search", command=lambda: self.search())

        self.root.mainloop()

    def log(self, message):
        self.messagebox.insert(END, f'{message}\n')
        self.messagebox.see(END)

    # Searching based on word
    def search(self):
        try:
            """Search for the given string in file and return lines containing that string,
                    along with line numbers"""
            line_number = 0
            list_of_results = []
            file_name = 'myFileMonitor.log'
            # ------------------------------------------------------------------
            # HOW CAN I DO THIS BELOW USER INPUT INSIDE THE TEXT WIDGET & SEARCH??
            string_to_search = input("What do you want to search in the Log file? : ")
            # ------------------------------------------------------------------ 
            # Open the file in read only mode
            with open(file_name, 'r') as read_obj:
                # Read all lines in the file one by one
                for line in read_obj:
                    # For each line, check if line contains the string
                    line_number += 1
                    if string_to_search in line:
                        # If yes, then add the line number & line as a tuple in the list
                        list_of_results.append((line_number, line.rstrip()))

            # Return list of tuples containing line numbers and lines where string is found
            # print('Total matched lines : ', len(list_of_results))
            self.log(f"Total matched lines :  {len(list_of_results)} ")

            # Display matching word with line number from log file
            for element in list_of_results:
                # print('Line = ', element[0], ' :: ', element[1])
                self.log(f"Line = {element[0]}  ::  {element[1]}")

        except FileNotFoundError:
            self.log("Exception error: File not exist!")


if __name__ == '__main__':
    MAIN()

【问题讨论】:

    标签: python tkinter search user-input


    【解决方案1】:

    您可以在文本小部件中放置一个条目,但这很快就会变得很奇怪,请参见示例:

    from tkinter import *
    
    root = Tk()
    root.geometry('500x300')
    
    text = Text(root)
    text.pack(padx=10, pady=10)
    text.pack_propagate(False)  # Do not allow contents to affect size
    text.insert('end', '''This is the first line.
    This is the second line.
    This is the third line.
    This is the fourth line.
    This is the fifth line.''')
    
    entry = Entry(text, bg='wheat')
    entry.pack(padx=20, pady=30, anchor='w')
    entry.insert(0, "search")
    
    root.mainloop()
    

    我建议您改为尝试使用对话框来输入搜索条件。看看Dialog Windows

    【讨论】:

    • 非常感谢您的想法。找到easygui,它工作得很好:)
    猜你喜欢
    • 2017-06-28
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多