Python Tkinter - 如何用不同的颜色突出显示多个字符串?

问题描述 投票:0回答:1

我有一个 code reader.py,它连接到 FTP 服务器,读取日志文件并在日志发生变化时实时更新它。这是“突出显示文本”按钮,用于突出显示“修改”条目 tkinter 小部件中的文本。但我希望它用 key:value 突出显示文本文件 (colors.txt) 中的文本(也是新出现的),其中“key”是要搜索的文本,“value”是用于突出显示该文本的颜色。

读者.py

import tkinter as tk
import pysftp
import time
import threading

current_read_thread = None
current_stop_event = None

root = tk.Tk()
root.geometry('1200x700')
frame = tk.Frame(root)
frame.place(x=15, y=10)
scroll = tk.Scrollbar(frame)
t = tk.Text(frame, width=183, height=45, yscrollcommand=scroll.set)
scroll.config(command=t.yview)
scroll.pack(side='right', fill='y')

def readdata(text,dir,logfile,stop_event):
    t.delete(1.0, tk.END)
    t.insert(tk.END, text+'LOADING...\n\n')
    cnopts = pysftp.CnOpts()
    cnopts.hostkeys = None
    sftp = pysftp.Connection('ip', username='user', password='pass', cnopts=cnopts)
    sftp.chdir('logs')
    sftp.chdir(dir) 
    active_log = logfile 
    with sftp.open(active_log, mode='r') as file:
        old_text = file.read().decode('ASCII')
        t.insert(tk.END, old_text)
        t.see('end')
    while not stop_event.is_set():
        with sftp.open(active_log, mode='r') as file:
            new_text = file.read().decode('ASCII')
        if new_text != old_text:
            t.insert(tk.END, new_text[len(old_text):])
            root.update()
            t.see('end')
            old_text = new_text
        time.sleep(1)

def start_thread(text,dir,logfile):
    global current_read_thread
    global current_stop_event
    if current_read_thread:
        current_stop_event.set()
        current_read_thread.join()
        current_read_thread = None
    current_stop_event = threading.Event()
    current_read_thread = threading.Thread(target=readdata,args=(text,dir,logfile,current_stop_event))
    current_read_thread.start()

def find():
    t.tag_remove('found', '1.0', tk.END)
    if ser := modify.get():
        idx = '1.0'
        while 1:
            idx = t.search(ser, idx, nocase=1, stopindex=tk.END)
            if not idx: break
            lastidx = '%s+%dc' % (idx, len(ser))
            t.tag_add('found', idx, lastidx)
            idx = lastidx
        t.tag_config('found', background='yellow')
    modify.focus_set()

buttons = tk.Frame()
b0 = tk.Button(buttons, text='USB0', command=lambda:start_thread('USB0: ','USB0','active.log'))
highlight = tk.Button(buttons, text='Highlight text',command=find)
modify = tk.Entry(buttons)
modify.pack(side=tk.RIGHT)
buttons.pack()
b0.pack(in_=buttons, side=tk.LEFT, padx=10)
highlight.pack(in_=buttons, side=tk.LEFT, padx=10)

frame.pack(fill='both',expand=True)
t.pack(fill='both',expand=True)

tk.mainloop()

示例 color.txt 文件

run_network=yellow
failed=green
something else happened=blue

我设法编写了函数来剥离和解析这个文本文件:

myObject = {}
def print_values():
    with open('colors.txt', 'r') as f:
        for line in f.readlines():
            key, value = line.rstrip("\n").split("=")
            myObject[key] = value
            print(key+":"+value)

# print result:
# run_network:yellow
# failed:green
# something else happened:blue

现在我想将这些键和值放入 readdata() 函数,因此每个选择的文本都将以特定的、它自己的颜色突出显示 - 也许我们可以删除此条目并保留“突出显示文本”按钮以某种方式打开/关闭突出显示?我怎样才能实现这样的目标?

python tkinter
1个回答
0
投票

阅读标签的使用。您可以将标签添加到文本小部件中的文本区域,并且可以将颜色与标签相关联。您可以在调用文本小部件的

insert
方法时应用标签,也可以使用
tag_add
方法将它们应用到预先存在的文本上。

© www.soinside.com 2019 - 2024. All rights reserved.