0
votes

I know we can add embedded widgets in a Text widget using Text method .window_create().But is it possible to add other widgets onto this embedded widget?

For example, I have a Text widget, I want to add a Frame widget under each line, and would like to use this embedded Frame widget as a container for adding e.g. Label widget to display features and annotations for specific part of the text.

How could I achieve, or is there an alternative way?

Here is some example code:

from tkinter import *

root = Tk()
myText = Text(root)
myText.pack()

text = """ACAACATACGAGCCGGAAGCATAAAG
TGTAAAGCCTGGGGTGCCTAATGAGT
GAGCTAACTCACATTAGGCTGAATTA
GGCGCGCCT"""

mylist = text.splitlines()

for row in range(len(mylist)):    
    myText.insert('end', mylist[row])
    myText.insert("end", '\n')
    myText.window_create('end', window=Frame(myText, width=180), stretch=1)
    myText.insert("end", '\n')

root.mainloop()

The above code will generate this:

enter image description here

With this example code above, how can I add additional widget (e.g. Labels) on those Frames, so that I can display descriptions on certain fragments of the text.

Thanks for helping!!

1
You add labels to the frame the same way you add labels to any other frame. Have you tried that? - Bryan Oakley
@ Bryan Oakley, sorry Bryan, I don't quite understand what you mean. There is no variable associated to the Frame object(s) in my example code, how to I refer them? Do you mean something similar as the answer posted below by @acw1668? Or would you please share an example? Thanks! - Zhenhua Xu
"There is no variable associated to the Frame object(s) in my example code, how to I refer them?" - by saving a reference to the frame in a variable. - Bryan Oakley
I get it, Thanks. - Zhenhua Xu

1 Answers

1
votes

You can store the frames in a list and then use the list to access the individual frame that you want to add labels to it:

frames = []  # store the frames
for row in range(len(mylist)):    
    myText.insert('end', mylist[row])
    myText.insert("end", '\n')
    frames.append(Frame(myText, width=180)) # create frame and store it in frames
    myText.window_create('end', window=frames[-1], stretch=1)
    myText.insert("end", '\n')

# add a label to each frame
for i, frame in enumerate(frames, 1):
    Label(frame, text=f"Hello in frame #{i}").pack()