I
I
id_666i2018-11-12 20:20:40
Python
id_666i, 2018-11-12 20:20:40

How to make word counter in tkinter text widget?

Hello, I want to make a counter of words/letters/etc that will count words/letters/etc from the text widget
I don’t know how to do it, there is such an option (self-written)

self.text = Text(width=200, height=100, fg='black', wrap=WORD, yscrollcommand=scrollbar.set)
        self.text.pack()

        textLen = str(len(self.text.get(1.0))) 

        self.wordCounter = tk.Label(toolbarBottom, justify="left" , bg="#d7d8e0", text="Слов в тексте: " + textLen)
        self.wordCounter.pack()

but it always shows "1"

Answer the question

In order to leave comments, you need to log in

3 answer(s)
Y
yahabrovec, 2018-11-12
@id_666i

Listen, when you use the .get function it returns you all the text that is inside the widget. For example, she returned you 'Some text'.
you write

counter = 0
for word in text:
       if word == ' ' #пробелы не считаем
             pass
       else:
            counter += 1

I think you understand the meaning

V
Vladislav Klimanov, 2018-11-12
@ahmpro

you need to bind the update of the counter on keystrokes

def toolbar(self):
        .....
        self.wordCounter = tk.Label(toolbarBottom, justify="left", bg="#d7d8e0", text="Символов в тексте: 0")
        self.wordCounter.pack()
        self.text.bind('<KeyPress>', self.on_textfield_update)
        self.text.bind('<KeyRelease>', self.on_textfield_update)
        .....

    def on_textfield_update(self, event):
        symbols = len(self.text.get('1.0', END).strip())
        self.wordCounter['text'] = 'Символов в тексте: {}'.format(symbols)

I
id_666i, 2018-11-12
@id_666i

Unfortunately it doesn't work either.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question