Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

issue with for loop in tkinter

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)
like image 561
ido rozen Avatar asked Jul 26 '26 18:07

ido rozen


1 Answers

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()
like image 199
Delrius Euphoria Avatar answered Jul 28 '26 09:07

Delrius Euphoria



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!