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?
JavaScript
x
31
31
1
from tkinter import *
2
from tkinter import scrolledtext
3
4
root = Tk()
5
6
dataFrame = Frame(root)
7
recFrame = Frame(root)
8
9
dataLabel = Label(root, text="Dados").grid(column=0, row=0)
10
dataInput = scrolledtext.ScrolledText(root, width=3, height=10)
11
dataInput.grid(column=0, row=1)
12
13
dataFrame.grid(column=0)
14
15
# Counts how many times the text appears
16
dataText = dataInput.get("1.0", "end-1c")
17
label = Label(recFrame, text=dataText)
18
labelCount = label['text'].count("1r#")
19
20
21
recPeTitle = Label(recFrame, text="P", width=3)
22
recPeTitle.grid(column=0,row=1)
23
24
# Here is where I want to "print" the count on a Label
25
recPe1 = Label(recFrame, text=labelCount)
26
recPe1.grid(column=0, row=2)
27
28
recFrame.grid(column=1, row=1, sticky=NW)
29
30
root.mainloop()
31
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:
JavaScript
1
35
35
1
from tkinter import *
2
from tkinter import scrolledtext
3
4
5
def update(event):
6
dataText = dataInput.get("1.0", "end-1c")
7
8
labelCount = dataText.count("1r#")
9
recPe1.config(text=labelCount)
10
11
12
root = Tk()
13
14
dataFrame = Frame(root)
15
recFrame = Frame(root)
16
17
dataLabel = Label(root, text="Dados").grid(column=0, row=0)
18
19
dataInput = scrolledtext.ScrolledText(root, width=3, height=10)
20
dataInput.bind("<KeyPress>", update)
21
dataInput.grid(column=0, row=1)
22
23
dataFrame.grid(column=0)
24
25
recPeTitle = Label(recFrame, text="P", width=3)
26
recPeTitle.grid(column=0,row=1)
27
28
# Here is where I want to "print" the count on a Label
29
recPe1 = Label(recFrame, text='0')
30
recPe1.grid(column=0, row=2)
31
32
recFrame.grid(column=1, row=1, sticky=NW)
33
34
root.mainloop()
35