如何使用tkinter中的下拉菜单创建条目?

2024-04-20 07:41:04 发布

您现在位置:Python中文网/ 问答频道 /正文

你们中有谁知道,如何创建一个搜索行,比如一个带有Entry()的搜索行,以及一个下拉菜单,比如在谷歌中,搜索行下面的这些建议

请原谅我的错误。我对这个完全陌生


Tags: 错误建议entry下拉菜单陌生
1条回答
网友
1楼 · 发布于 2024-04-20 07:41:04

您可以创建一个自定义的组合框,而无需按钮。我们只需删除按钮元素并减少填充。现在它看起来像一个条目,但下拉列表将出现在“向下键”上

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:]))

相关问题 更多 >