Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

Python My code for highlighting the keyword is not working

Sp4ut

New Coder
Python:
for sheet_name, df in self.sheets.items():
            # Verifica se pelo menos uma das colunas relevantes existe na folha
            if not any(col in df.columns for col in relevant_cols):
                continue
           
            # Cria uma máscara de pesquisa global (em todas as colunas da folha)
            combined_mask = pd.Series([False] * len(df))
            for col in df.columns:
                combined_mask |= df[col].astype(str).str.lower().str.contains(query, na=False)
           
            filtered_df = df[combined_mask]
            if not filtered_df.empty:
                results_found = True
                # Itera sobre cada linha filtrada e extrai os valores das colunas relevantes
                for index, row in filtered_df.iterrows():
                    projeto_val = str(row.get("Designação do Projeto", ""))
                    promotor_val = str(row.get("Promotor Líder", ""))
                    univ_val = str(row.get("Universidades Envolvidas", ""))
                    co_promotores_val = str(row.get("Co-promotores", ""))
                    cod_val = str(row.get("Código de Operação", ""))
                   
                    # Se houver múltiplas entradas separadas por ';', formata a string
                    co_promotores_val = '; '.join([e.strip() for e in co_promotores_val.split(';')]) if co_promotores_val else ""
                   
                    item_id = self.tree.insert(
                       "", tk.END, values=(projeto_val, promotor_val, univ_val, co_promotores_val, cod_val)
                    )
                def add_highlighter():
                    if sheet_name in self.sheets.items():
                        print()
                        print(sheet_name.replace(sheet_name,'\033[44;33m{}\033[m'))
                    if not results_found:
                        messagebox.showinfo("Resultado", "Nenhum resultado encontrado.")
 
Last edited by a moderator:
for sheet_name, df in self.sheets.items():
# Verifica se pelo menos uma das colunas relevantes existe na folha
if not any(col in df.columns for col in relevant_cols):
continue

# Cria uma máscara de pesquisa global (em todas as colunas da folha)
combined_mask = pd.Series([False] * len(df))
for col in df.columns:
combined_mask |= df[col].astype(str).str.lower().str.contains(query, na=False)

filtered_df = df[combined_mask]
if not filtered_df.empty:
results_found = True
# Itera sobre cada linha filtrada e extrai os valores das colunas relevantes
for index, row in filtered_df.iterrows():
projeto_val = str(row.get("Designação do Projeto", ""))
promotor_val = str(row.get("Promotor Líder", ""))
univ_val = str(row.get("Universidades Envolvidas", ""))
co_promotores_val = str(row.get("Co-promotores", ""))
cod_val = str(row.get("Código de Operação", ""))

# Se houver múltiplas entradas separadas por ';', formata a string
co_promotores_val = '; '.join([e.strip() for e in co_promotores_val.split(';')]) if co_promotores_val else ""

item_id = self.tree.insert(
"", tk.END, values=(projeto_val, promotor_val, univ_val, co_promotores_val, cod_val)
)
def add_highlighter():
if sheet_name in self.sheets.items():
print()
print(sheet_name.replace(sheet_name,'\033[44;33m{}\033[m'))
if not results_found:
messagebox.showinfo("Resultado", "Nenhum resultado encontrado.")


Difficult due to your unformatted code snippet. Did you mean something like this?


Python:
import pandas as pd
import tkinter as tk
from tkinter import ttk, messagebox 

class SheetProcessor:
    def __init__(self, sheets, tree):
        self.sheets = sheets 
        self.tree = tree 
    
    def process_sheets(self, query):
        results_found = False 

        for sheet_name, df in self.sheets.items():
            
            relevant_cols = ["Test"]
            if not any(col in df.columns for col in relevant_cols):
                continue

            # Create a global search mask across all columns
            combined_mask = pd.Series([False] * len(df))
            for col in df.columns:
                combined_mask |= df[col].astype(str).str.lower().str.contains(query, na=False)

            filtered_df = df[combined_mask]
            if not filtered_df.empty:
                results_found = True
            
            # Iterate over each filtered row and extract relevant values
            for _, row in filtered_df.iterrows():
                projeto_val = str(row.get("Designação do Projeto", ""))
                promotor_val = str(row.get("Promotor Líder", ""))
                univ_val = str(row.get("Universidades Envolvidas", ""))
                co_promotores_val = str(row.get("Co-promotores", ""))
                cod_val = str(row.get("Código de Operação", ""))

                # Format multiple entries separated by ';'
                co_promotores_val = '; '.join(
                    [e.strip() for e in co_promotores_val.split(';')]
                ) if co_promotores_val else ""

                # Insert the item into the Treeview
                self.tree.insert(
                    "", tk.END, values=(projeto_val, promotor_val, univ_val, co_promotores_val, cod_val)
                )

        self.add_highlighter(sheet_name, results_found)

    def add_highlighter(self, sheet_name, results_found):
        if sheet_name in self.sheets:
            print(f'\033[44;33m{sheet_name}\033[m')  # Highlight sheet name in console

        if not results_found:
            messagebox.showinfo("Resultado", "Nenhum resultado encontrado.")

# Example:
if __name__ == "__main__":
    sheets = {
        "Sheet1": pd.DataFrame({
            "Test": ["example1", "example2"],
            "Designação do Projeto": ["Project A", "Project B"],
            "Promotor Líder": ["Leader A", "Leader B"],
        })
    }

    root = tk.Tk()
    tree = ttk.Treeview(root) 

    processor = SheetProcessor(sheets, tree)
    processor.process_sheets("example")
 
Your code has a few issues that might be causing the highlighting to not work properly. Here are some key problems and potential fixes:


Problems in Your Code:​


  1. Incorrect self.sheets.items() check inside add_highlighter():
    • sheet_name in self.sheets.items() is incorrect. self.sheets.items() returns key-value pairs, so this check will always fail.
    • You should check if sheet_name in self.sheets: instead.
  2. Incorrect use of ANSI escape codes for highlighting (\033[44;33m{}\033[m)
    • You're using an escape sequence for terminal output, which won’t work in a Tkinter-based GUI.
  3. The function add_highlighter() is defined inside a loop but is never called.
    • Even if it's correctly implemented, it needs to be executed for the highlighting to take effect.
  4. results_found is defined outside add_highlighter() but checked inside it.
    • If no results are found, the messagebox.showinfo will never run because it's inside a function that is never executed.



Fixing Your Code:​


Here’s a corrected version with a proper approach to highlighting in Tkinter’s Treeview:


Python:
import tkinter as tk
from tkinter import ttk, messagebox
import pandas as pd

class KeywordHighlighter:
    def __init__(self, root, sheets):
        self.root = root
        self.sheets = sheets  # Dictionary of sheet names and DataFrames
        self.tree = ttk.Treeview(root, columns=("Projeto", "Promotor", "Universidades", "Co-promotores", "Código"), show="headings")
        self.tree.pack(expand=True, fill="both")

        # Define column headings
        for col in ("Projeto", "Promotor", "Universidades", "Co-promotores", "Código"):
            self.tree.heading(col, text=col)

    def highlight_keyword(self, query):
        results_found = False
        relevant_cols = ["Designação do Projeto", "Promotor Líder", "Universidades Envolvidas", "Co-promotores", "Código de Operação"]

        for sheet_name, df in self.sheets.items():
            if not any(col in df.columns for col in relevant_cols):
                continue  # Skip if no relevant columns

            combined_mask = pd.Series([False] * len(df))  # Initialize mask
            for col in df.columns:
                combined_mask |= df[col].astype(str).str.lower().str.contains(query.lower(), na=False)

            filtered_df = df[combined_mask]

            if not filtered_df.empty:
                results_found = True
                for index, row in filtered_df.iterrows():
                    projeto_val = str(row.get("Designação do Projeto", ""))
                    promotor_val = str(row.get("Promotor Líder", ""))
                    univ_val = str(row.get("Universidades Envolvidas", ""))
                    co_promotores_val = str(row.get("Co-promotores", ""))
                    cod_val = str(row.get("Código de Operação", ""))

                    co_promotores_val = '; '.join([e.strip() for e in co_promotores_val.split(';')]) if co_promotores_val else ""

                    item_id = self.tree.insert("", tk.END, values=(projeto_val, promotor_val, univ_val, co_promotores_val, cod_val))

                    # Highlighting the row if the keyword is found
                    self.tree.tag_configure("highlight", background="yellow", foreground="black")
                    self.tree.item(item_id, tags=("highlight",))

        if not results_found:
            messagebox.showinfo("Resultado", "Nenhum resultado encontrado.")

# Sample Usage:
if __name__ == "__main__":
    root = tk.Tk()
    root.title("Keyword Highlighter")

    # Example Data
    data = {
        "Designação do Projeto": ["Project A", "Project B", "AI Research"],
        "Promotor Líder": ["Company X", "Company Y", "University Z"],
        "Universidades Envolvidas": ["MIT; Stanford", "Harvard", "Oxford"],
        "Co-promotores": ["Lab A", "Lab B", "Lab C"],
        "Código de Operação": ["1234", "5678", "91011"]
    }
    df = pd.DataFrame(data)
    sheets = {"Sheet1": df}

    app = KeywordHighlighter(root, sheets)

    # Search for keyword "AI"
    app.highlight_keyword("AI")

    root.mainloop()



Key Fixes & Features:​


✅ Properly Filtering Data:


  • Ensures the query is converted to lowercase for a case-insensitive search.
  • Uses combined_mask to filter relevant rows efficiently.

✅ Tkinter Treeview Row Highlighting:


  • The tag_configure("highlight", background="yellow", foreground="black") function adds a yellow highlight to rows containing the keyword.
  • self.tree.item(item_id, tags=("highlight",)) applies the highlight tag to the correct rows.

✅ Improved UI Handling:


  • If no results are found, it shows messagebox.showinfo("Resultado", "Nenhum resultado encontrado.").
  • The table auto-expands in the Tkinter window.



​

 
Back
Top Bottom