Home > Software engineering >  issue with for loop in tkinter
issue with for loop in tkinter

Time:07-21

so im working on a small project in and im trying to get input from the user using the entry widget and then comparing and seeing if any of the words in the input matches one or more of the words inside a list , for some reason it dosent work and the program dosent read and trying to match and instad jumps straight into showing the lable that it shouldve print only if one of the words matches :

e = Entry(window, width=40, borderwidth=3, font='Arial 20')
e.place(rely=0.2, relx=0.24)
r1 = Label(window, text="good", font='Arial 20')

def s_command():
    x = ["egg","milk","rice","salt"]
    s_input = e.get().split(" ")
    for s_input in x:
        r1.pack()

S_button = Button(window, text="Search", font='Arial 22', width=8, command=s_command)
S_button.place(rely=0.25, relx=0.4)

CodePudding user response:

Here one approach is, you can use a nested loop, because you need to be checking if the user enters more than an item and if any of the items exists in the list.

def s_command():
    x = ["egg","milk","rice","salt"]
    s_input = e.get().split(" ")

    for inp in s_input: # Go through input list
        for item in x: # Go through items list
            if inp == item: # If an input is same as item
                r1.pack() # Show the widget
                break # Stop the loop because you want to check if any item matches
            else: 
                r1.pack_forget() # Remove the label
        # Make the nested loop break the outer loop
        else:
            continue
        break

Next approach is to just use a single loop(as seen in JRiggles's answer) and if the item exists in list using in, like:

def s_command():
    x = ["egg", "milk", "rice", "salt"]
    s_input = e.get().split(' ')
    
    for inp in s_input:
        if inp in x:
            r1.pack()
            break
        else:
            r1.pack_forget()

If you had to check just one item with the list then it would be much easier:

def s_command():
    x = ["egg", "milk", "rice", "salt"]
    s_input = e.get() # Only single item so no need to split
    
    if s_input in x:
        r1.pack()
    else:
        r1.pack_forget()

CodePudding user response:

Okay, here's a working (if a bit pared down) example of what I think you're after

import tkinter as tk
window = tk.Tk()
e = tk.Entry(window)
e.pack()

search_val = tk.StringVar()

# this label updates whenever search_val is set
lbl = tk.Label(window, textvariable=search_val)
lbl.pack()


def cmd():
    x = ['egg', 'milk', 'rice', 'salt']
    usr_in = e.get().split(' ')
    matches = ''
    for value in x:
        if value in usr_in:
            matches  = value   ' '  # append all matches found in 'x'
    # update the label if there's a match from the list 'x'
    search_val.set(matches)


btn = tk.Button(window, text='Search', command=cmd)
btn.pack()

window.mainloop()
  • Related