Create multiple Text widgets on every tab

64 views Asked by At

What do I need: create Text widgets on every tab.

My code right now:

    for i in range(len(result)):
        tab[i] = ttk.Frame(tabControl)
        tabControl.add(tab[i], text=i)
    tabControl.pack(fill='both', expand=True)
    for i in range(len(result)):
        textwrite[i] = Text(tab[i])
        textwrite[i].pack(fill='both', expand=True)
        scrollbar_fortext[i] = Scrollbar(tab[i], orient='vertical', command=textwrite[i].yview)
        scrollbar_fortext[i].pack(fill='both', expand=True, sticky=NS)  

Expected behavior: every tab has a Text widget.

Received behavior:

NameError: name 'textwrite' is not defined
2

There are 2 answers

0
Suramuthu R On

Use a dict if you want to declare dynamic variable. As your code is not complete, I've kept len(result) as 5. Change the code according to your requirement. The options for '-sticky' are only -after, -anchor, -before, -expand, -fill, -in, -ipadx, -ipady, -padx, -pady, or -side. There is no option such as NS. So, I've removed that. Change accordingly. This is how the code should be.

from tkinter import *
from tkinter import ttk

root = Tk()
root.geometry('700x500')

tabControl = ttk.Notebook(root, width=700)
tabControl.pack()

dct = {}
#for testing purpose I've given length of result as 5.Change the code accordingly.
for i in range(5):
    dct[f'tab_{i}'] = ttk.Frame(tabControl)
    tabControl.add(dct[f'tab_{i}'], text = f'{i}')
    dct[f'scrollbar_fortext_{i}'] = Scrollbar(dct[f'tab_{i}'], orient='vertical')
    dct[f'scrollbar_fortext_{i}'].pack(fill='both', expand=True)
    
    
root.mainloop()
        
        
        
        
0
Abhijith On

You need to initialize the tab, textwrite and scrollbar_fortext variables (preferably as empty dictionaries) before creating items with indexing. Also, you should use only one for loop and generate the tab, textwrite and scrollbar_fortext.
Use tabControl.pack() either before or after the for loop. It will be better if you change the variable name tab to something else.