Home > database >  How to get radio button index in python?
How to get radio button index in python?

Time:10-12

I am having trouble while getting index of selected radio button item. The selected value of radio button can be grab from .get() function. but how can I get the index for that value. Please anyone Help ! Here is my code

from tkinter import *

itemList = ['item 1', 'item 2', 'item 3', 'item 4']

def sel():
   print ("You selected the option "   str(var.get()))

root = Tk()
var = StringVar()
var.set(0)

for item in itemList:
    radioButton = Radiobutton(root, text=item, variable=var, value=item, command=sel)
    radioButton.pack(anchor=W)
   # radioButtonIndex=?

   
root.mainloop() 

CodePudding user response:

Using the List in-built index() method you can get the index of the selected value.

from tkinter import *

itemList = ['item 1', 'item 2', 'item 3', 'item 4']


def sel():
    print(f"You selected the option is {var.get()}, index is {itemList.index(var.get())}")


root = Tk()
var = StringVar()
var.set("0")

for item in itemList:
    radioButton = Radiobutton(root, text=item, variable=var, value=item, command=sel)
    radioButton.pack(anchor=W)


root.mainloop()
  • Related