Skip to content
Advertisement

Update a Label while the app is running without a button on Tkinter

I want to make a label that keeps counting how many times the user typed a certain word(in this case “1r#”) in a ScrolledText without needing to make a button to update the label. Can I make a loop? If so, how could I do it?

from tkinter import *
from tkinter import scrolledtext

root = Tk()

dataFrame = Frame(root)
recFrame = Frame(root)

dataLabel = Label(root, text="Dados").grid(column=0, row=0)
dataInput = scrolledtext.ScrolledText(root, width=3, height=10)
dataInput.grid(column=0, row=1)

dataFrame.grid(column=0)

# Counts how many times the text appears
dataText = dataInput.get("1.0", "end-1c")
label = Label(recFrame, text=dataText)
labelCount = label['text'].count("1r#")


recPeTitle = Label(recFrame, text="P", width=3)
recPeTitle.grid(column=0,row=1)

# Here is where I want to "print" the count on a Label
recPe1 = Label(recFrame, text=labelCount)
recPe1.grid(column=0, row=2)

recFrame.grid(column=1, row=1, sticky=NW)

root.mainloop()

Every word the program will look for are three characters long, if it helps.

Advertisement

Answer

You don’t need another loop. Simply, bind <KeyPress> to a function then update the count.

See the example below:

from tkinter import *
from tkinter import scrolledtext


def update(event):
    dataText = dataInput.get("1.0", "end-1c")
    
    labelCount = dataText.count("1r#")
    recPe1.config(text=labelCount)
    

root = Tk()

dataFrame = Frame(root)
recFrame = Frame(root)

dataLabel = Label(root, text="Dados").grid(column=0, row=0)

dataInput = scrolledtext.ScrolledText(root, width=3, height=10)
dataInput.bind("<KeyPress>", update)
dataInput.grid(column=0, row=1)

dataFrame.grid(column=0)

recPeTitle = Label(recFrame, text="P", width=3)
recPeTitle.grid(column=0,row=1)

# Here is where I want to "print" the count on a Label
recPe1 = Label(recFrame, text='0')
recPe1.grid(column=0, row=2)

recFrame.grid(column=1, row=1, sticky=NW)

root.mainloop()
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement