Search code examples
pythontkinterbuttonwidgettkinter-entry

Is there a way to test if tkinter entry contain a specific word or not?


I use a tkinter for entry and search by entry boxes, is there a code i can write it to give me a message if the entry box contain a specific word (for example: bachelor) Thanks


Solution

  • @Sujay was telling you to use something like this:

    import tkinter as tk
    from tkinter.messagebox import showinfo
    
    
    def check_word_in_entry(*args):
        user_input = entry.get()
        # If you don't want casing to matter, change this to:
        # if "hi" in user_input.lower():
        if "hi" in user_input:
            # print("The word \"hi\" is inside the entry.")
            showinfo(message="The word \"hi\" is inside the entry.")
    
    
    root = tk.Tk()
    root.geometry("400x400")
    
    variable = tk.StringVar(root)
    variable.trace("w", check_word_in_entry)
    
    entry = tk.Entry(root, textvar=variable)
    entry.pack()
    
    root.mainloop()
    

    It calls check_word_in_entry each time the text inside the entry is changed. And it checks if "hi" is inside the entry's text.