Python Tkinter Text widget extremely slow when add

2019-08-03 23:30发布

I have a sizeable piece of text contained in a Python Tkinter Text widget. I need to colour the background of each letter in the text, individually, depending on another variable. I do this by adding tags with tag_add. The problem is that the widget responsiveness slows down significantly when all the tags are added. Without the tags everything runs fluently. What can I do?

This is a minimal example of the code:

from Tkinter import *
import tkMessageBox
import Tkinter as ttk
import tkFileDialog
import csv

import ttk
from ttk import *

root = Tk()

root.minsize(width=1280, height=600)
root.maxsize(width=1280, height=600)

w, h = root.winfo_screenwidth(), root.winfo_screenheight()
x = (w/2) - 640
y = (h/2) - 300
root.geometry('%dx%d+%d+%d' % (1200, 640, x, y-80))

#Horizontal (x) Scroll bar
xscrollbar = Scrollbar(orient=HORIZONTAL)
xscrollbar.pack(side=BOTTOM, fill=X)
#Vertical (y) Scroll Bar
yscrollbar = Scrollbar()
yscrollbar.pack(side=RIGHT, fill=Y)

MSA_text1 = Text(height=30, width=150, xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set)
MSA_text1.pack()
MSA_text1.configure(wrap="none", font="TkFixedFont")
MSA_text1.place(x=105,y=0)

#Configure the scrollbars
xscrollbar.config(command=MSA_text1.xview)
yscrollbar.config(command=MSA_text1.yview)


for number2 in range(1,20):

    MSA_text1.insert(END, "SPAELHSFTHCGQTALTLQGATTTEASNILRSCHACRGGNPQHQMPRGHIRRGLLPNHIWQGDITHFKYKNTLYRLHVWVDTFSGAISATQKRKETSSEAISSLLQAIAHLGKPSYINTDNGPAYISQDFLNMCTSLAIRHTTHVPYNPTSSGLVERSNGILKTLLYKYFTDKPDLPMDNALSIALWTINHLNVLTNCHKTRWQLHHSPRLQPIPETRSLSNKQTHWYYFKLPGLNSRQWKGPQEALQEAAGAALIPVSASSAQWIPWRLLKRAACPRPVGGPADPKEKDLQHHG" +"\n")

    for number in range(0,295):

        MSA_text1.tag_add(number, str(number2)+"."+str(number), str(number2)+"."+str(number+1))
        MSA_text1.tag_config(number, background="red", foreground="black")

MSA_text1.configure(state="disabled")

mainloop()

0条回答
登录 后发表回答