动态tkinter输入框

2024-10-01 17:26:58 发布

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

我想知道这是否可能。。。?在

想象一下一个tkinter应用程序,它有一个输入框小部件,用于输入PC名。一旦用户开始在框中键入内容,应用程序将根据您键入的内容显示可能的名称,因此您键入的越多,您看到的选项就越少,直到您只剩下一个选项,或者从可用选项中选择一个足够小的选项来单击它。在

如果这是TKTETH的可能,如果有人能指点我一个简单的例子太好了!在

我不能发布任何示例代码,因为这是一个一般问题而不是具体问题。在


Tags: 用户名称应用程序示例内容键入部件tkinter
1条回答
网友
1楼 · 发布于 2024-10-01 17:26:58

您可以将StringVar的一个实例与entry小部件相关联,然后对该实例进行跟踪,以便在值更改时调用回调。然后你可以在回调中做任何你想做的事情,更新一个列表,弹出一个窗口等等

下面是一个简单地根据输入内容过滤列表的示例。在

import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.choices = ("one", "two", "three", "four", "five", 
                        "six", "seven", "eight", "nine", "ten",
                        "eleven", "twelve", "thirteen", "fourteen",
                        "fifteen", "sixteen", "seventeen", "eighteen",
                        "nineteen", "twenty")

        self.entryVar = tk.StringVar()
        self.entry = tk.Entry(self, textvariable=self.entryVar)
        self.listbox = tk.Listbox(self)
        self.listbox.insert("end", *self.choices)

        self.entry.pack(side="top", fill="x")
        self.listbox.pack(side="top", fill="both", expand=True)

        self.entryVar.trace("w", self.show_choices)
        self.listbox.bind("<<ListboxSelect>>", self.on_listbox_select)

    def on_listbox_select(self, event):
        """Set the value based on the item that was clicked"""
        index = self.listbox.curselection()[0]
        data = self.listbox.get(index)
        self.entryVar.set(data)

    def show_choices(self, name1, name2, op):
        """Filter choices based on what was typed in the entry"""
        pattern = self.entryVar.get()
        choices = [x for x in self.choices if x.startswith(pattern)]
        self.listbox.delete(0, "end")
        self.listbox.insert("end", *choices)

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

相关问题 更多 >

    热门问题