2017-05-09 37 views
2

尝试添加搜索功能来搜索该代码中的关键词:添加线性搜索

button1 = tk.Button(f1, text='Year 12, Paper One', command=lambda:raise_frame(f2)).pack() 
button2 = tk.Button(f1, text='Year 12, Paper Two', command=lambda:raise_frame(f3)).pack() 
button3 = tk.Button(f1, text='Year 13, Paper One', command=lambda:raise_frame(f4)).pack() 
button4 = tk.Button(f1, text='Year 13, Paper Two', command=lambda:raise_frame(f5)).pack() 

tk.Label(f2, text="Year 12, Paper One").pack() 
tk.Button(f2, text="HOME", command=lambda:raise_frame(f1)).pack() 

tk.Label(f3, text="Year 12, Paper Two").pack() 
tk.Button(f3, text="HOME", command=lambda:raise_frame(f1)).pack() 
tk.Label(f4, text="Year 13, Paper One").pack() 
tk.Button(f4, text="HOME", command=lambda:raise_frame(f1)).pack() 
tk.Label(f5, text="Year 13, Paper Two").pack() 
tk.Button(f5, text="HOME", command=lambda:raise_frame(f1)).pack() 
raise_frame(f1) 
root.mainloop() 

,这是我创建了当前搜索 - 这是正确的,我应该把这个代码?

def sequentialSearch(alist, item): 
    pos = 0 
    found = False 

    while pos < len(alist) and not found: 
     if alist[pos:pos+len(list(item))] == list(item): 
      found = True 
     else: 
      pos = pos+1 

    return found 
+0

不知道发生了什么事情与搜索。你想看看'item'是否在'alist'中?为什么不只是'如果项目在alist:退货'或什么的? – Matthias

+0

所以即时添加每个按钮内的信息,我想要搜索一个词,用户从按钮的文本中输入 – jb23

回答

0

您可能想要将代码放在按钮的command的某处。

另外,如果我理解正确的话,可以缩短sequentialSearch功能颇有几分

def sequentialSearch(alist, item): 
    return item in alist 

Python的in运营商检查,看是否itemalist一员,我认为它只是一个顺序搜索它。

例子:

alist = ['a','b','c'] 
item = 'b' 
print(item in alist) # True 
item = 'd' 
print(item in alist) # False 
+0

因此,我会把它放在我的问题的顶部线之上? – jb23

+0

不是?你需要解释更多你想要做的事情。取决于物品是否被找到,应该发生什么?它是否适用于所有按钮?该搜索应该运行在每个按钮点击? (在这种情况下,你需要通过单击按钮来调用该函数,我认为这是我提到的'command') – Matthias