I have a Scrolledtext with Tkinter, and would like a command to fetch words that would be inside it

Asked

Viewed 308 times

-1

area = ScrolledText(jan, width=800, height=400)

Here I have a Scrolledtext, which is nothing more than a text box with a scrollbar, let’s say I typed enough content inside it and would like to search for such name ex: fuel, the function would appear something like an Entry and so type what I am looking for at the end would appear where I typed such a word a kind of "Ctrl" + "F" in Scrolledtext

I was able to detect if the content inserted in an entry is in the text box but I can not show only the line of the contents, see the example

ctf = Entry(top)
ctf.place(x=0, y=0)

def serch():
    cont = ctf.get()
    dent_text = area.get(1.0, END)
    if cont in todo:
        messagebox.showinfo(title="Pesquisa", message=("Aqui devia aparecer
 toda a linha mas se eu colocar ou cont para exibir mostrara apenas o 
 digitado na entry, se colocar dent_text, todo conteudo da ScrolledText sera 
 mostrado, eu queria exibir apenas a linha em que o cont esta)

csc = Button(top, text="OK", command=serch)
csc.place(x=130, y=0)
  • [link] http://www.bitforestinfo.com/2017/05/how-to-create-find-and-findall-features-in-tkinter-text-widget-python-magicstick-editor-part-9.html

1 answer

1


The "commando" that you are looking for is the method search() which has the parameters:

search(self, pattern, index, stopindex=None,
       forwards=None, backwards=None, exact=None,
       regexp=None, nocase=None, count=None, elide=None)

I set an example performed the search in widgets of the type Text and ScrolledText.

I didn’t follow your code because it’s not a minimal functional example.

Pipfle that was used:

[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true

[dev-packages]
pylint = "*"
autopep8 = "*"

[packages]

[requires]
python_version = "3.6"

Code:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Busca de palavras ou letras com Tkinter."""
import tkinter as tk
from tkinter import messagebox
from tkinter.scrolledtext import ScrolledText


class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack(expand=True, fill=tk.BOTH, padx=5, pady=5)
        self.create_widgets()

    def create_widgets(self):
        # Frame para organizar o entry e o button.
        frame_search = tk.Frame(self)
        frame_search.pack(side=tk.TOP, expand=True, fill=tk.X)

        self.entry_search = tk.Entry(master=frame_search)
        self.entry_search.pack(side=tk.LEFT, expand=True, fill=tk.X, padx=(0, 10))

        button_search = tk.Button(master=frame_search)
        button_search['text'] = 'Buscar'
        button_search['command'] = self.on_button_clicked
        button_search.pack(side=tk.RIGHT, fill=tk.X)

        # Frame para o ScrolledText.
        frame_text_area = tk.Frame(self)
        frame_text_area.pack(side=tk.BOTTOM, expand=True, fill=tk.BOTH)

        # self.text_area = tk.Text(frame_text_area)
        # self.text_area.insert(tk.END, 'ola mundo')
        # self.text_area.pack(side=tk.BOTTOM, pady=10)

        self.text_area = ScrolledText(frame_text_area)
        self.text_area.insert(tk.END, 'ola mundo')
        self.text_area.pack(side=tk.BOTTOM, pady=10)

    def on_button_clicked(self):
        # Contador para exibir quantas ocorrências houveram.
        words = 0

        # Pesquisa se inicia na linha 1, coluna 0.
        start = '1.0'

        # Coletando texto digitado no entry.
        entry = self.entry_search.get()

        # Se o entry estiver vazio não existe a necessidade de se pesquisar.
        if not entry:
            messagebox.showinfo('Alerta', 'Entry não pode estar vazio.')
        else:
            # Removendo a tag, pois a cada nova
            # pesquisa a posição pode variar.
            self.text_area.tag_delete('found')

            # Verificando o tamanho do texto digitado no entry.
            # Tamanho será utilizado para posicionamento.
            word_size = len(entry)

            # Laço de repetição ficará ativo até percorrer todas as posições.
            while True:
                # Realizando a pesquisa
                pos = self.text_area.search(pattern=entry, index=start, stopindex=tk.END, count=True)

                # Quando não houver mais posições é
                # exibindo o dialogo e o loop é encerado.
                if not pos:
                    messagebox.showinfo(
                        'Pesquisa finalizada',
                        f'{words} localizado(s) com: "{entry}"'
                    )
                    print(f'A pesquisa chegou ao fim {words} localizado(s)\n')
                    break

                print(f'Palavra/letra localizada na linha {pos[0]} e na coluna de {pos[2]}')

                # Adicionando a uma tag na posição em que o texto foi localizado.
                # Aqui está sendo utilizando ``word_size = len(entry)``
                # para determinar a posição final da cor de fundo do texto.
                self.text_area.tag_add('found', pos, (pos + f'+{word_size}c'))

                # Incrementando o contador.
                words += 1

                # Alterando o valor da variável ``start`` para que em
                # algum momento ele seja superior a stopindex=tk.END.
                start = pos + '+1c'

            # Configurando a tag que foi inserida em ``self.text_area``.
            self.text_area.tag_config('found', background='yellow')


if __name__ == '__main__':
    root = tk.Tk()
    root.title('Busca de palavras ou letras com Tkinter')
    app = Application(master=root)
    app.mainloop()

Obs: The code presented is only intended to illustrate a simple search.

Remember to analyze and change the code as your project needs.

If you find an error, or even if you think the code does not answer the question, remember to warn so that the answer can be changed or even removed.

  • I tested your code and it’s really the way I want it, however my source code is not last self method my code is very simple but at the time of passing your knowledge to my code even with the same version of your still having problems have you how to pass me your email so that I send the full source code? I think this would help a lot

  • 1

    [email protected] and my profile also has other contact forms: https://answall.com/users/93029/renato-cruz?tab=profile

Browser other questions tagged

You are not signed in. Login or sign up in order to post.