Can I assign and access variable inside Tkinter Listbox while for looping?

Viewed 59

I have been coding for two months. I want to use tkinter and Listbox and access variable "attached" to specific loop in a for loop.

Here is my code so far:

from tkinter import *
root = Tk()

listbox = Listbox(root)
listbox.pack()

number = 10
for i in range(number):
    listbox.insert(END, i)
    # here letter A, B, C, etc.?

def get_letter():
    print(listbox.get(listbox.curselection()))

btn = Button(root, text="Show letter from row", command=lambda: get_letter())
btn.pack()

mainloop()

In this program I would like to give (and show) every row in listbox a number value and corresponding letter value/variable in the backend (0 to A, 1 to B, etc.). At runtime I want to click a number, then press button and thus printing the letter. I commented the line where I suppose the letter value would be inserted, but I can't imagine a method. How would I go about doing this?

1 Answers

This is pretty easy, first of all define what all letters you want in a list, for example:

lst = ['A','D','B',....]

For this example I'm going to use every alphabet, but the looping will limit to number you set:

import string #only to get list of all alphabets

.... #same codes

number = 10 #number of alphabets you want to add
alpha = list(string.ascii_uppercase) #making a list of all alphabets 
for i in range(number):
    listbox.insert(END, alpha[i]) #indexing the list based on the iterated number

...#same codes

This will get you the alphabet, when you select them too.

Just to improve a bit further: You could add a line of binding that would get the value when you double click on the required item, like:

listbox.bind('<Double-Button-1>',lambda event=None:get_letter())

Notice that you asked for a change in the answer, this way you would get the index number of the alphabet:

def get_letter():
    print((listbox.curselection()[0]))  #indexing from the tuple 
Related