【问题标题】:Setting multiple fonts in tkinter textarea widget while using iterations使用迭代时在 tkinter textarea 小部件中设置多种字体
【发布时间】:2021-05-12 01:55:42
【问题描述】:

我目前正在 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", 20) )
        txtarea.insert(END, "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")

期望的输出:

看看不同的行有不同的字体吗?

实际输出:

请有人帮我解决这个问题吗?另外 , 由于 我 是 Stackoverflow 的 新手 , 欢迎 你 指出 我 犯 的 错误

【问题讨论】:

    标签: python user-interface tkinter tk


    【解决方案1】:

    为每条文本定义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()
    

    输出:

    【讨论】:

    • 这行得通,但你能告诉我如何在我的情况下修改它吗?
    • 什么是my situation
    • 我的意思是,正如我在上面的代码中提到的,我正在使用 API,并使用迭代来输出数据。就我而言,我不可能知道数据将是什么,所以你能帮我解决这个问题吗?
    【解决方案2】:

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

    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', font = ('Calibri', 20, 'bold'))
    
    root.mainloop()
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-09
      • 2017-04-09
      • 1970-01-01
      • 1970-01-01
      • 2012-05-27
      • 1970-01-01
      • 1970-01-01
      • 2013-06-26
      相关资源
      最近更新 更多