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

Tkinter Combobox에서 선택한 옵션의 인덱스를 얻는 방법은 무엇입니까?

<시간/>

항목의 드롭다운 목록을 만들고 사용자가 목록의 항목을 선택하도록 하려면 콤보 상자 위젯을 사용할 수 있습니다. 콤보 상자 위젯을 사용하면 항목 목록을 즉시 선택할 수 있는 드롭다운 목록을 만들 수 있습니다. 그러나 콤보 상자 위젯에서 선택한 항목의 색인을 얻으려면 get() 방법. get() 메소드는 항목의 인덱스로 알려진 선택된 항목의 정수를 반환합니다.

예시

작동 방식을 확인하기 위해 예를 들어 보겠습니다. 이 예에서는 드롭다운 목록에 요일 목록을 만들었으며 사용자가 드롭다운 목록에서 요일을 선택할 때마다 선택한 항목의 인덱스를 인쇄하고 Label 위젯에 표시합니다. 인덱스를 인쇄하려면 주어진 인덱스를 문자열로 형변환하여 문자열을 연결할 수 있습니다.

# 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")

# Create a function to clear the combobox
def clear_cb():
   cb.set('')
   
# Define Days Tuple
days= ('Sun','Mon','Tue','Wed','Thu','Fri','Sat')

# Function to print the index of selected option in Combobox
def callback(*arg):
   Label(win, text= "The value at index " + str(cb.current()) + " is" + " "+ str(var.get()), font= ('Helvetica 12')).pack()
   
# Create a combobox widget
var= StringVar()
cb= ttk.Combobox(win, textvariable= var)
cb['values']= days
cb['state']= 'readonly'
cb.pack(fill='x',padx= 5, pady=5)

# Set the tracing for the given variable
var.trace('w', callback)

# Create a button to clear the selected combobox text value
button= Button(win, text= "Clear", command= clear_cb)
button.pack()

win.mainloop()

출력

위의 코드를 실행하면 날짜 목록과 함께 콤보 상자 위젯이 표시됩니다. 목록에서 날짜를 선택할 때마다 레이블 위젯에 색인과 해당 항목이 인쇄됩니다.

Tkinter Combobox에서 선택한 옵션의 인덱스를 얻는 방법은 무엇입니까?