使用迭代时在 tkinter textarea 小部件中设置多种字体

问题描述

我目前正在 tkinter 中创建一个项目,该项目涉及使用 textarea 小部件。 我想在文本区域小部件中设置多种字体,但唯一的问题是,我正在使用迭代,所以我无法弄清楚。

我关心的代码

for i in range(len(news_list)):
        txtarea.configure(font=("Bahnschrift",20) )
        txtarea.insert(END,news_list[i]["title"] + "\n\n" )
        txtarea.configure(font=("Bahnschrift","Description:" +  str(news_list[i]["description"]) + "\n\n" )
        txtarea.insert(END,"Read More at:" +  str(news_list[i]["url"]) + "\n\n" )
        txtarea.insert(END,"--------------------------------- " + "\n")

所需的输出

See how different lines have different fonts ?

看看不同的线条有不同的字体?

实际输出

enter image description here

请问有人可以帮我吗?另外,由于我是 Stackoverflow 的新手,非常欢迎您指出我所犯的错误

解决方法

为每段文本定义tag

import tkinter as tk

TEXT = [("mountain",'title'),("[maʊntən]","monospaces"),("a large natural elevation of the earth's surface rising abruptly from the surrounding level",'normal')]

root = tk.Tk()
t = tk.Text(root)
t.pack()
t.tag_configure("title",font=("Bahnschrift bold",20))
t.tag_configure("monospaces",font=("Lucida",12))
t.tag_configure("normal",font=("Arial",14))

for text in TEXT:
    t.insert(tk.END,f'{text[0]}\n',text[1])
tk.mainloop()

输出:

enter image description here

,

当您要显示固定文本时,您可以使用标签。例如,运行以下代码 -

import tkinter as tk

root = tk.Tk()
tbox = tk.Text(root,height = 5,width = 20,font = ('Calibri',15))
tbox.pack()

# adding text to the text box
tbox.insert(tk.END,"Hello\nWe are exited for \nspace exploration.")
#adding tags
tbox.tag_add('Tag1','3.0','3.17')
tbox.tag_config('Tag1',20,'bold'))

root.mainloop()

注意:创建标签的语法是-

<text box object>.tag_add(<tag name>,<starting character>,<ending character>)