【发布时间】: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