Search code examples
tkinterpython-3.7tkinter-canvastkinter-entrytkinter-layout

How to return an alert for a specific input using Tkinter?


I have created a mock search engine using Tkinter. I want the user to input the word "test" in the search engine and hit submit. This should return an alert. If the user inserts anything other than the word "test", then I want the search engine to return nothing. I have already created the interface for the mock search engine but the part that takes in user input isn't working. Here is my code below:

import tkinter as tk
root = tk.Tk()
canvas1=tk.Canvas(root,width=400,height=300,relief='raised')
canvas1.pack()
label1 = tk.Label(root,text='LookUp')
label1.config(fg='blue',font=('times',30,'bold'))
canvas1.create_window(200,100,window=label1)
entry1 = tk.Entry (root)
canvas1.create_window(200,140,window=entry1)

def values():
     userinput = tk.StringVar(entry1.get())
     if userinput == 'test':
             Output = ('Alert Executed')
             label_Output = tk.Label(root,text=Alert,bg='red')
             canvas1.create_window(270,200,window=label_Output)                     

     else:
             Output = ('')
             label_Output = tk.Label(root,text= Alert)
             canvas1.create_window(270,200,window=label_Output)

button1=tk.Button(root,text='Search',command=values,bg='green',fg='white')
canvas1.create_window(200,180,window=button1)

root.mainloop()

Solution

  • The userinput variable needs to refer to entry1.get()

    The label_Output needs to have your Output variable as its text

    import tkinter as tk
    root = tk.Tk()
    canvas1=tk.Canvas(root,width=400,height=300,relief='raised')
    canvas1.pack()
    label1 = tk.Label(root,text='LookUp')
    label1.config(fg='blue',font=('times',30,'bold'))
    canvas1.create_window(200,100,window=label1)
    entry1 = tk.Entry (root)
    canvas1.create_window(200,140,window=entry1)
    
    def values():
         userinput = entry1.get()
         if userinput == 'test':
                 Output = ('Alert Executed')
                 label_Output = tk.Label(root,text=Output,bg='red')
                 canvas1.create_window(270,200,window=label_Output)                     
    
         else:
                 Output = ('')
                 label_Output = tk.Label(root,text= Output)
                 canvas1.create_window(270,200,window=label_Output)
    
    button1=tk.Button(root,text='Search',command=values,bg='green',fg='white')
    canvas1.create_window(200,180,window=button1)
    
    root.mainloop()