您知道吗,如何创建一个搜索行,例如带有Entry()的带有下拉菜单的搜索行,例如Google在该搜索行下方的这些建议??
请原谅我的错误。我对此完全陌生。
答案 0 :(得分:1)
您可以创建没有按钮的自定义组合框。我们只需要删除按钮元素并减少填充。现在,它看起来像一个条目,但下拉列表将显示在Key-Down上。
import tkinter as tk
import tkinter.ttk as ttk
class HistoryCombobox(ttk.Combobox):
"""Remove the dropdown from a combobox and use it for displaying a limited
set of historical entries for the entry widget.
<Key-Down> to show the list.
It is up to the programmer when to add new entries into the history via `add()`"""
def __init__(self, master, **kwargs):
"""Initialize the custom combobox and intercept the length option."""
kwargs["style"] = "History.Combobox"
self.length = 10
if "length" in kwargs:
self.length = kwargs["length"]
del kwargs["length"]
super(HistoryCombobox, self).__init__(master, **kwargs)
def add(self, item):
"""Add a new history item to the top of the list"""
values = list(self.cget("values"))
values.insert(0, item)
self.configure(values=values[:self.length])
@staticmethod
def register(master):
"""Create a combobox with no button."""
style = ttk.Style(master)
style.layout("History.Combobox",
[('Combobox.border', {'sticky': 'nswe', 'children':
[('Combobox.padding', {'expand': '1', 'sticky': 'nswe', 'children':
[('Combobox.background', {'sticky': 'nswe', 'children':
[('Combobox.focus', {'expand': '1', 'sticky': 'nswe', 'children':
[('Combobox.textarea', {'sticky': 'nswe'})]})]})]})]})])
style.configure("History.Combobox", padding=(1, 1, 1, 1))
style.map("History.Combobox", **style.map("TCombobox"))
def on_add(ev):
"""Update the history list"""
item = ev.widget.get()
ev.widget.delete(0, tk.END)
ev.widget.add(item)
def main(args=None):
root = tk.Tk()
root.wm_geometry("600x320")
HistoryCombobox.register(root)
w = HistoryCombobox(root, length=8, width=40)
w.bind("<Return>", on_add)
for item in ["one", "two", "three"]:
w.add(item)
w.place(x=0, y=0)
return 0
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv[1:]))