所以我在做一个小项目,我试着从用户那里获取信息

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)

推荐答案

这里需要一个嵌套循环,因为需要判断用户是否输入了多个项目,以及列表中是否存在任何项目.

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

如果你只需要在列表中勾选一个项目,那么这会容易得多:

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()

Python相关问答推荐

如何让剧作家等待Python中出现特定cookie(然后返回它)?

删除任何仅包含字符(或不包含其他数字值的邮政编码)的观察

Pandas 都是(),但有一个门槛

图像 pyramid .难以创建所需的合成图像

在Python中动态计算范围

使用Python更新字典中的值

Polars asof在下一个可用日期加入

Flash只从html表单中获取一个值

搜索按钮不工作,Python tkinter

Odoo16:模板中使用的docs变量在哪里定义?

无法在Spyder上的Pandas中将本地CSV转换为数据帧

Python协议不兼容警告

将字节序列解码为Unicode字符串

Django抛出重复的键值违反唯一约束错误

BeatuifulSoup从欧洲志愿者服务中获取数据和解析:一个从EU-Site收集机会的小铲子

无法在盐流道中获得柱子

使用Scikit的ValueError-了解

如何使用Polars从AWS S3读取镶木地板文件

如何将django url参数传递给模板&S url方法?

如何通过函数的强式路径动态导入函数?