如何获取选择组合框中选定选项的索引

时间:2017-03-22 06:26:50

标签: python tkinter combobox python-2.x

以下代码让我打印出Combobox中的选定值,但我需要打印(获取)列表中所选项目的索引号。你能告诉我怎么做吗?

<form class="form" role="form" method="POST" action="login.php" accept-charset="UTF-8" id="login-nav">
    <div class="form-group">
        <label class="sr-only" for="email">Email address</label>
        <input type="email" class="form-control" id="email" placeholder="Email address" required>
    </div>
    <div class="form-group">
        <label class="sr-only" for="password">Password</label>
        <input type="password" class="form-control" id="password" placeholder="Password" required>
    </div>
    <div class="form-group">
    <button type="submit" class="btn btn-primary btn-block" id="submit">Sign in</button>
    </div>
</form>

2 个答案:

答案 0 :(得分:3)

在组合框上使用current方法。

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()

答案 1 :(得分:1)

如果您将bind()current()合并,则可以。

这是一个快速演示:

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()