Igor Dragushhak
Igor Dragushhak

Reputation: 637

Can I set different fonts for different lines in a tkinter text widget?

I am making a dictionary. And I have a list of lines (strings) of a particular word. I need it to look like this:enter image description here

Upvotes: 0

Views: 2672

Answers (2)

figbeam
figbeam

Reputation: 7176

You can use a text widget and style the dictionary elements differently:

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

Upvotes: 2

user10433052
user10433052

Reputation:

You would want to create 4-5 labels if you want different fonts. It would be structured like:

  • First label = mountain
  • Second label = ['mauntin]
  • Third label = ropa
  • Fourth label = definition

Visit Python's tkinter docs for more info on font configurations for labels.

Upvotes: 0

Related Questions