Найти - Пользователи
Полная версия: Изучение tkinter
Начало » Python для новичков » Изучение tkinter
1
ZeD
Добрый день! Изучаю модуль tkinter. Столкнулся с такой проблемой. Вот самый простой код:

 from tkinter import *
a=['a','b','c','d']
def printName():
    for i in a:
        text.insert(END, f' {i} \n')
root = Tk()
button = Button(root, text='Данные', command=printName)
button.grid()
text = Text(root,width=45, height=15)
text.grid()
root.mainloop()

Необходимо в виджет text вывести значения списка а. Вывожу. Вопрос в следующем: как сделать так, чтоб значения списка а выводились каждый своим, заранее определённым, цветом?
Ранее при работе в консоле использовал библиотеку colorama и всё решалось просто. Как тут это реализовать? Спасибо!
PEHDOM
ZeD в ткинтер Text форматирование осущевтляеться с помощью тегов, примерно так
 #
import tkinter as tk
root = tk.Tk()
root.title("Begueradj")
text = tk.Text(root)
# Insert some text
text.insert(tk.INSERT, "Security ")
text.insert(tk.END, " Pentesting ")
text.insert(tk.END, "Hacking ")
text.insert(tk.END, "Coding")
text.pack()
# Create some tags
text.tag_add("one", "1.0", "1.8")
text.tag_add("two", "1.10", "1.20")
text.tag_add("three", "1.21", "1.28")
text.tag_add("four", "1.29", "1.36")
#Configure the tags
text.tag_config("one", background="yellow", foreground="blue")
text.tag_config("two", background="black", foreground="green")
text.tag_config("three", background="blue", foreground="yellow")
text.tag_config("four", background="red", foreground="black")
#Start the program
root.mainloop()
боле детально что оно умеет смотри в документации. https://docs.python.org/3/library/tkinter.html
ZeD
Спасибо за ответ, но это немного не то. Смысл в вопросе следующий. Имеется список:
 a=['a','b','c','d']
раньше работая в косоле я задавал цвет каждому элементу списка используя модуль colorama. Например:
 a=[
Fore.RED+'a',
Fore.YELLOW+'b',
Fore.GREEN+'c',
Fore.YELLOW+'d']
далее мой код выполнял определённое преобразование со списком а и выводил в консоле например список:
 b=[
Fore.YELLOW+'b',
Fore.GREEN+'c']
В консоле значения списка b подсвечивались своими ранее заданными цветами. То, что предлагаете вы не совсем то. У вас цвет и текст задаются когда выводятся. А в моём коде не известно каким получиться список b. Поэтому спрашиваю есть ли возможность заранее, как используя colorama, задать цвет каждому элементу списка а? Спасибо!
PEHDOM
ZeD ХЗ может и есть чтото такое, но только не в стандартной либе.
Если нет, то вам придется написать это самому. По сути ничего архисложного, нужно чтобы программа искала положение заданых слов и добавляла эти положения к нужным тегам.
очень упрощенный пример найденый в интернетах за 5 минут, подсвечивает красным все слова “strings” в тексте, естевенно можно добавить другие слова и другую подсветку:
 #
import tkinter as tk
from tkinter import *
class CustomText(tk.Text):
    '''A text widget with a new method, highlight_pattern()
    example:
    text = CustomText()
    text.tag_configure("red", foreground="#ff0000")
    text.highlight_pattern("this should be red", "red")
    The highlight_pattern method is a simplified python
    version of the tcl code at http://wiki.tcl.tk/3246
    '''
    def __init__(self, *args, **kwargs):
        tk.Text.__init__(self, *args, **kwargs)
    def highlight_pattern(self, pattern, tag, start="1.0", end="end",
                          regexp=False):
        '''Apply the given tag to all text that matches the given pattern
        If 'regexp' is set to True, pattern will be treated as a regular
        expression according to Tcl's regular expression syntax.
        '''
        start = self.index(start)
        end = self.index(end)
        self.mark_set("matchStart", start)
        self.mark_set("matchEnd", start)
        self.mark_set("searchLimit", end)
        count = tk.IntVar()
        while True:
            index = self.search(pattern, "matchEnd","searchLimit",
                                count=count, regexp=regexp)
            if index == "": break
            if count.get() == 0: break # degenerate pattern which matches zero-length strings
            self.mark_set("matchStart", index)
            self.mark_set("matchEnd", "%s+%sc" % (index, count.get()))
            self.tag_add(tag, "matchStart", "matchEnd")
root = Tk()
texts = 'This is a long strings. How many strings are there'
x = 'strings'
text = CustomText(root)   #This is a class that i use to look to highlight x string in texts
text.insert(END, texts)
text.tag_configure("red", foreground="#ff0000")
text.highlight_pattern(x, "red")
text.grid(row = 0 ,column = 1)
root.mainloop()
ZeD
Спасибо огромное! Попробую. Если у кого вдруг появятся ещё мысли, очень буду признателен!
xam1816
ZeD
Если у кого вдруг появятся ещё мысли
может вам выводить каждый элемент отдельным
  Label(text=text, fg='color').grid(row=,column =)
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB