gpt4 book ai didi

python - tkinter 中的 for 循环问题

转载 作者:行者123 更新时间:2023-12-05 03:21:00 26 4
gpt4 key购买 nike

所以我正在做一个小项目,我试图从用户那里获得输入使用条目小部件,然后比较并查看输入中的任何单词是否与列表中的一个或多个单词匹配,由于某种原因它起作用并且程序发送读取并尝试匹配并且 instad 直接跳转到显示标签,只有当其中一个词匹配时它才应该打印:

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

下一个方法是只使用一个循环(如 JRiggles 的回答中所示),如果该项目存在于使用 in 的列表中,例如:

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

如果您只需要检查列表中的一项,那么它会容易得多:

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 - tkinter 中的 for 循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73057182/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com