i want to make the labels for the current length of the Text in a tkinter Text widget but my code doing last text box so what i have to do?
from tkinter import *
win=Tk()
win.geometry("700x350")
text_all=[]
label_all=[]
for i in range(1,11):
text=Text(win, width=20, height=1, font=('Calibri 14'))
text.grid(row=i-1,column=0)
text_all.append(text)
label=Label(win, text="Total Characters", justify=CENTER, font=('11'))
label.grid(row=i-1, column=1)
label_all.append(label)
for i in range(1,11):
def update(event):
label_all[i-1].config(text="Total Characters: "+str(len(text_all[i-1].get("1.0", 'end-1c'))))
text_all[i-1].bind('<KeyPress>', update)
text_all[i-1].bind('<KeyRelease>', update)
win.mainloop()
When update() is executed, the value of i will be the last assigned value after the for loop, i.e. 10.
You need to capture the required value of i and pass this value to update() using argument default value:
for i in range(1, 11):
def update(event, i=i):
label_all[i-1].config(text="Total Characters: "+str(len(text_all[i-1].get("1.0", 'end-1c'))))
...
Also you can merge the two for loops into one:
for i in range(1,11):
def update(event, i=i):
label_all[i-1].config(text="Total Characters: "+str(len(text_all[i-1].get("1.0", 'end-1c'))))
text=Text(win, width=20, height=1, font=('Calibri 14'))
text.grid(row=i-1,column=0)
text.bind('<KeyPress>', update)
text.bind('<KeyRelease>', update)
text_all.append(text)
label=Label(win, text="Total Characters", justify=CENTER, font=('11'))
label.grid(row=i-1, column=1)
label_all.append(label)
All I had to do to get your code working was to remove the geometry statement in order to allow Text to determine window size and change update(event) to update(event, i = i):
Everything else works as is!
from tkinter import *
win=Tk()
# remove and let text widget determine width of window
# win.geometry("700x350")
text_all=[]
label_all=[]
for i in range(1,11):
text=Text(win, width = 40, height=1, font=('Calibri 14'))
text.grid(row=i-1,column=0, sticky=EW)
text_all.append(text)
label=Label(win, text="Total Characters", justify=CENTER, font=('11'))
label.grid(row=i-1, column=1, sticky=EW)
label_all.append(label)
for i in range(1,11):
def update(event, i = i):
label_all[i-1].config(text="Total Characters: "+str(len(text_all[i-1].get("1.0", 'end-1c'))))
text_all[i-1].bind('<KeyPress>', update)
text_all[i-1].bind('<KeyRelease>', update)
win.mainloop()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With