0

Please note I am new to Tkinter. I have also looked at text tags, but I am not sure how to apply that in this case.

I would like to change the styling of text based on its location in a list (really a list of lists).

The structure of "results_list" is:

[["header1","entry1"],["header2","entry2"]...]

I would like each "header" to have a different font styling than the entries. I am unsure of how to do this / where to find more info (I have tried reading the documentation, but I could not figure it out). Also note: each entry may have more than one element in it. The GUI I am making is an app with definitions; each header is a dictionary and each entry is a single definition (for some words, there are multiple definitions).

Code so far:

    def printDictToFrame(self,results_list):
        txt = tk.Text(self.SEARCH_RESULTS_FRAME,width = 34,height=20,pady=5,padx=2,background='#d9d9d9',relief=RIDGE)
        txt.place(x=10,y=10)
            for r_list in results_list:
            header = r_list[0]
            entry = r_list[1]
            txt.insert(tk.END, "{}\n".format(header.center(25,"*")))
                for single_result in entry:
                    txt.insert(tk.END,single_result+"\n")

I have done a makeshift "header" using .center. If possible, I would like the headers to be centered as well.

To clarify, the text such as "三省堂 スーパー大辞林" should be bold and centered, while the entry underneath should be regular text. This pattern should hold for each header/entry combo.

What I currently have. The '三省堂 スーパー大辞林' is one of the 'headers

Steak
  • 514
  • 3
  • 15
  • _"Also note: each entry may have more than one element in it. "_ - please give an example of that. Your description is a little bit vague. Also, will every first element in the list (eg: "header1", "header2") be unique, or will multiple items in the list potentially use the same tags? – Bryan Oakley Dec 23 '20 at 23:25
  • I apologize. Each element is just a string. The headers will have the same tags, and the entries will as well (meaning there are two types of tags, headers and entries). – Steak Dec 24 '20 at 10:36

1 Answers1

2

You can assign the header line a tag and use tag_config() to center the line and use bold font.

Below is an example:

import tkinter as tk

root = tk.Tk()

txt = tk.Text(root, width=34, height=20, pady=5, padx=2, bg="#d9d9d9", relief=tk.RIDGE)
txt.pack(padx=10, pady=10)

# line with tag "header" will be centered and using bold font
txt.tag_config("header", justify="center", font=(None,10,"bold"))

results_list = [
  ["header1", ["entry 1"]],
  ["三省堂 スーパー大辞林", ["entry 2.1", "entry 2.2"]]
]

for header, entries in results_list:
  txt.insert(tk.END, "{}\n".format(header), "header") # associate header with tag "header"
  for single_result in entries:
    txt.insert(tk.END, "{}\n".format(single_result))

root.mainloop()

And the result:

enter image description here

acw1668
  • 40,144
  • 5
  • 22
  • 34