How to Get Index of Selected Option inTkinter Combobox

喜夏-厌秋 提交于 2020-01-05 07:11:12

问题


Following code lets me to print out the selected value from the Combobox, but I need to print(get) the indexnumber of selected item in the list. Can you please let me know how to do that?

import Tkinter
import tkMessageBox
from Tkinter import *
import ttk
from ttk import *

app = Tk()

def OptionCallBack(*args):
    print variable.get()

variable = StringVar(app)
variable.set("Select From List")
variable.trace('w', OptionCallBack)

so = ttk.Combobox(app, textvariable=variable)
so.config(values =('Tracing Upstream', 'Tracing Downstream','Find Path'))
so.grid(row=1, column=4, sticky='E', padx=10)


app.mainloop()

回答1:


Use the current method on the combobox.

import Tkinter
import tkMessageBox
from Tkinter import *
import ttk
from ttk import *

app = Tk()

def OptionCallBack(*args):
    print variable.get()
    print so.current()

variable = StringVar(app)
variable.set("Select From List")
variable.trace('w', OptionCallBack)


so = ttk.Combobox(app, textvariable=variable)
so.config(values =('Tracing Upstream', 'Tracing Downstream','Find Path'))
so.grid(row=1, column=4, sticky='E', padx=10)


app.mainloop()



回答2:


Yes you can if you combine bind() with current().

Here is a quick demo:

import Tkinter
import tkMessageBox
from Tkinter import *
import ttk
from ttk import *

app = Tk()

def display_selected_item_index(event): 
   global so
   print 'index of this item is: {}\n'.format(so.current())

def OptionCallBack(*args):
    print variable.get()

variable = StringVar(app)
variable.set("Select From List")
variable.trace('w', OptionCallBack)

so = ttk.Combobox(app, textvariable=variable)
so.config(values =('Tracing Upstream', 'Tracing Downstream','Find Path'))
so.grid(row=1, column=4, sticky='E', padx=10)    
so.bind("<<ComboboxSelected>>", display_selected_item_index)  

app.mainloop()


来源:https://stackoverflow.com/questions/42944214/how-to-get-index-of-selected-option-intkinter-combobox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!