Попробуйте адаптировать этот код к вашему приложению.
Он использует Text
виджет с тегами для создания цветного текста.Таким образом, вы должны заменить свои Label
виджеты на Text
.
from Tkinter import *
class Sorting(Frame):
def __init__(self):
Frame.__init__(self)
self.master.title("Sorting")
self.master.rowconfigure(5, weight=1)
self.master.columnconfigure(5, weight=1)
self.grid(sticky=W+E+N+S )
nums = [10, 20, 8, 5, 7] # example of entry
result = sorted(nums) # sorted result = [3 ,5 , 8, 10 ,20]
# the color list holds the items changing position when sortened
color = [ind for ind, (x, y) in enumerate(zip(nums, result)) if x != y]
entry_num = ''.join('%4i' % num for num in nums)
sort_nums = ''.join('%4i' % num for num in result)
l1 = Label(self, text="entry", width=25, height=1)
l1.grid(row=0, column=1, sticky=N)
t_entry = Text(self, width=25, height=2)
t_entry.grid(row=1, column=1, sticky=N)
t_entry.insert(END, entry_num)
l2 = Label(self, text='sorted', width=25, height=1)
l2.grid(row=2, column=1, sticky=N)
t_sorted = Text(self, width=25, height=2)
t_sorted.grid(row=3, column=1, sticky=N)
t_sorted.insert(END, sort_nums)
t_sorted.tag_config('red_tag', foreground='red')
for pos in color:
a = '1.%i' % (4 * pos)
b = '1.%i' % (4 * pos + 4)
t_sorted.tag_add('red_tag', a, b)
if __name__ == "__main__":
Sorting().mainloop()
![enter image description here](https://i.stack.imgur.com/nZas7.png)