?
要实现这个功能,可以通过以下步骤:
import tkinter as tk
from tkinter import scrolledtext
import re
window = tk.Tk()
window.title("日志搜索")
window.geometry("400x300")
# 创建文本框
text_box = scrolledtext.ScrolledText(window, height=10)
text_box.pack()
# 创建搜索按钮
search_button = tk.Button(window, text="搜索", command=search_logs)
search_button.pack()
# 创建滚动文本框用于显示搜索结果
result_box = scrolledtext.ScrolledText(window, height=10)
result_box.pack()
window.mainloop()
def search_logs():
keyword = text_box.get("1.0", tk.END).strip() # 获取文本框中的关键字
if keyword:
try:
# 打开日志文件并逐行搜索
with open("logfile.txt", "r") as file:
lines = file.readlines()
matches = [line for line in lines if re.search(keyword, line, re.IGNORECASE)]
# 显示搜索结果
result_box.delete("1.0", tk.END) # 清空结果框
if matches:
for match in matches:
result_box.insert(tk.END, match)
else:
result_box.insert(tk.END, "未找到匹配的日志行。")
except FileNotFoundError:
result_box.insert(tk.END, "日志文件不存在。")
else:
result_box.insert(tk.END, "请输入关键字进行搜索。")
请注意,这里仅提供了一个简单的示例,你可以根据实际需求进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云