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

时间:2018-10-06 12:23:17

标签: python python-3.x tkinter

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

2 个答案:

答案 0 :(得分:1)

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

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()

答案 1 :(得分:0)

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

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

访问Python's tkinter docs,以获得有关标签字体配置的更多信息。