Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Tkinter에서 자동 완성 기능이 있는 콤보 상자를 만드는 방법은 무엇입니까?

<시간/>

Tkinter Combobox 위젯은 애플리케이션에서 드롭다운 메뉴를 구현하는 데 유용한 위젯 중 하나입니다. 그 위에 있는 Entry 위젯과 ListBox 위젯의 조합을 사용합니다. 항목 필드에 항목 이름(메뉴 목록에 있는 경우)을 입력하여 메뉴 항목을 선택할 수 있습니다. 그러나 때때로 메뉴 항목을 선택하기 위해 자동 완성을 사용해야 하는 경우가 있습니다.

자동 완성 콤보 상자를 만들기 위해 먼저 메뉴를 나열하는 목록 상자와 선택한 메뉴를 표시하는 항목 위젯을 만듭니다. "Keyrelease" 이벤트를 항목 위젯과 결합하여 목록에서 특정 키워드를 검색할 수 있습니다. 항목이 있으면 목록 상자 위젯을 업데이트합니다.

예시

이 예에서는 다음과 같은 두 가지 함수를 만들 것입니다.

  • check(e) 함수 입력한 항목이 목록에 있는지 여부를 찾습니다. 항목이 입력된 키워드와 일치하면 특정 데이터를 삽입하여 항목 위젯을 업데이트합니다.
  • 함수 업데이트(데이터) 항목 위젯에 값을 삽입하여 항목 상자를 업데이트합니다.
# 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 스크립트를 실행하면 항목 위젯과 ListBox가 있는 창이 표시됩니다. 키워드를 입력할 때마다 입력한 키워드와 일치하는 결과를 보여주는 ListBox 위젯이 업데이트됩니다.

Tkinter에서 자동 완성 기능이 있는 콤보 상자를 만드는 방법은 무엇입니까?