代码之家  ›  专栏  ›  技术社区  ›  Igor Dragushhak

我可以为tkinter文本小部件中的不同行设置不同的字体吗?

  •  0
  • Igor Dragushhak  · 技术社区  · 7 年前

    我正在做一本字典。我有一个特定单词的行(字符串)列表。我需要它看起来像这样: enter image description here

    2 回复  |  直到 7 年前
        1
  •  1
  •   figbeam    7 年前

    您可以使用文本小部件并以不同方式设置字典元素的样式:

    from tkinter import *
    
    root = Tk()
    root.geometry('400x250')
    
    # Create text widget
    word_text = Text(root, wrap='word', padx=10, pady=10)
    word_text.pack(fill='both', padx=10, pady=10)
    
    # Define attributes for dictionary entry
    word = 'mountain'
    pronunciation = '[ˈmount(ə)n]'
    word_class = 'noun'
    description = '''a large natural elevation of the earth's surface rising abruptly from the surrounding level; a large steep hill'''
    
    # Insert text sections
    word_text.insert('end', word+'\n')
    word_text.insert('end', pronunciation+'\n')
    word_text.insert('end', word_class+'\n')
    word_text.insert('end', description)
    
    # Tag and style text sections
    word_text.tag_add('word','1.0','1.end')
    word_text.tag_config('word', font='arial 15 bold')  # Set font, size and style
    word_text.tag_add('pronunciation','2.0','2.end')
    word_text.tag_config('pronunciation', font='arial 13 normal')
    word_text.tag_add('word_class','3.0','3.end')
    word_text.tag_config('word_class', font='arial 12 italic', lmargin1=30,
                         spacing1=10, spacing3=15)  # Set margin and spacing
    word_text.tag_add('description','4.0','99.end')
    word_text.tag_config('description', font='none 12', lmargin1=15, lmargin2=15)
    
    root.mainloop()
    
        2
  •  0
  •   user10433052 user10433052    7 年前

    如果需要不同的字体,则需要创建4-5个标签。其结构如下:

    • 第一个标签=
    • 第二个标签=['mauntin]
    • 第三个标签=ropa

    访问 Python's tkinter docs 有关标签字体配置的详细信息。