如何在 Tkinter 中创建带有自动完成功能的组合框?


Tkinter Combobox 小部件是用于在应用程序中实现下拉菜单的有用小部件之一。它在其顶部使用了 Entry 小部件和 ListBox 小部件的组合。我们可以通过在 Entry 字段中键入项目名称(如果它存在于菜单列表中)来选择菜单项。但是,有时,可能存在需要使用自动完成功能来选择菜单项的情况。

为了创建一个自动完成功能的 Combobox,我们将首先创建一个 Listbox 来列出菜单,以及一个 Entry 小部件来显示所选菜单。您可以将“Keyrelease”事件与 Entry 小部件绑定,以在列表中搜索特定关键字。如果该项目存在,我们将更新 Listbox 小部件。

示例

在这个示例中,我们将创建两个函数,这样:

  • 函数 **check(e)** 将查找输入的项目是否存在于列表中。如果该项目与输入的关键字匹配,我们将通过插入特定数据来更新 Entry 小部件。
  • 函数 **update(data)** 将通过在 Entry 小部件中插入值来更新 Entry 框。
# Import the Required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame or window
win= Tk()

# Set the size of the window
win.geometry("700x350")

# Set the title of the window
win.title("Combobox- TutorialsPoint")

# Update the Entry widget with the selected item in list
def check(e):
   v= entry.get()
      if v=='':
      data= values
   else:
      data=[]
      for item in values:
         if v.lower() in item.lower():
            data.append(item)
   update(data)

def update(data):
   # Clear the Combobox
   menu.delete(0, END)
   # Add values to the combobox
   for value in data:
      menu.insert(END,value)


# Add a Label widget
label= Label(win, text= "Demo Combobox Widget", font= ('Helvetica 15
bold'), background= "green3")
label.pack(padx= 10, pady= 25)

# Add a Bottom Label
text= Label(win, text="Select a Programming Language")
text.pack(padx= 15,pady= 20)

# Create an Entry widget
entry= Entry(win, width= 35)
entry.pack()
entry.bind('<KeyRelease>',check)

# Create a Listbox widget to display the list of items
menu= Listbox(win)
menu.pack()

# Create a list of all the menu items
values= ['Python', 'C++', 'Java','Ruby on Rails', 'Rust',
'GoLang','Objective-C', 'C# ', 'PHP', 'Swift', 'JavaScript']

# Add values to our combobox
update(values)

# Binding the combobox onclick

win.mainloop()

输出

运行上述 Python 脚本将显示一个带有 Entry 小部件和 ListBox 的窗口。每当我们输入一个关键字时,它将更新 ListBox 小部件,显示与输入关键字匹配的结果。

更新于:2021年6月7日

3K+ 浏览量

启动您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.