[Asm] 纯文本查看 复制代码 import tkinter as tk
from tkinter import ttk
import openpyxl
def search_excel(file_path, sheet_name, keyword):
wb = openpyxl.load_workbook(file_path)
sheet = wb[sheet_name]
result = []
for row in sheet.iter_rows(values_only=True):
if keyword.lower() in ' '.join(str(cell) for cell in row).lower():
result.append(row)
return result
def perform_search(*args):
file_path = 'data.xlsx' # Excel文件路径
sheet_name = 'Sheet1' # 表格名称
keyword = search_var.get()
results = search_excel(file_path, sheet_name, keyword)
# 清空Treeview中的数据
for i in treeview.get_children():
treeview.delete(i)
# 插入查询结果到Treeview中
for index, row in enumerate(results, start=1):
treeview.insert('', 'end', values=(str(index),) + row)
# 创建GUI窗口
window = tk.Tk()
window.title("Excel查询软件")
# 设置窗口大小为600x300
window.geometry("1000x300")
window_width = 1000
window_height = 300
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
x = (screen_width - window_width) // 2
y = (screen_height - window_height) // 2
window.geometry(f"{window_width}x{window_height}+{x}+{y}")
# 查询输入框
search_label = tk.Label(window, text="请输入关键字:")
search_label.pack()
search_var = tk.StringVar()
def on_search_change(*args):
perform_search()
# 跟踪输入框的值变化
search_var.trace('w', on_search_change)
search_entry = tk.Entry(window, textvariable=search_var)
search_entry.pack()
# 查询结果显示区域
treeview_frame = ttk.Frame(window)
treeview_frame.pack(side=tk.TOP, fill=tk.BOTH)
treeview_scrollbar = ttk.Scrollbar(treeview_frame)
treeview_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# 设置查询结果显示窗口大小为600x300
treeview = ttk.Treeview(treeview_frame, yscrollcommand=treeview_scrollbar.set, height=10)
treeview.pack(fill=tk.BOTH, expand=True)
treeview_scrollbar.config(command=treeview.yview)
# 定义表格列名和列宽
columns = [('索引列', -200), ('列1', -50), ('列2', 120), ('列3', 140), ('列4', 140)] # 根据实际情况修改列名和列宽
# 设置Treeview列名
treeview['columns'] = [col[0] for col in columns]
# 设置每列的属性和宽度
treeview.column('#0', width=columns[0][1])
for index, (column_name, column_width) in enumerate(columns[1:], start=1):
treeview.column('#' + str(index), width=column_width)
treeview.heading('#' + str(index), text=column_name)
# 运行窗口主循环
window.mainloop()
请问下大佬,如何在以上内容,添加一个 让搜索出来显示的文字颜色与表格中文字颜色一致呢? |