1

I cant print the key value of the dic when I print the value of each list

I tried with the code I wrote down!

import tkinter as tk
from tkinter import ttk

limit_before_list = [0]
max_posts_list = [0]
max_comments_list = [0]
limit_before = 'limit_before'
max_posts = 'max_posts'
max_comments = 'max_comments'


def mostrar_nombre(event):
    listbox = event.widget
    index = listbox.curselection()
    value = listbox.get(index[0])
    print(pestaña_text)
    print(value)


pestañas = {
    limit_before: list(range(0, 160, 10)),
    max_posts: list(range(0, 410, 10)),
    max_comments: list(range(0, 4100, 100)),
}

note = ttk.Notebook()

for pestaña, items in pestañas.items():
    frame = ttk.Frame(note)
    note.add(frame, text=pestaña)
    listbox = tk.Listbox(frame, exportselection=False)
    listbox.grid(row=0, column=0)
    listbox.bind("<<ListboxSelect>>", mostrar_nombre)

    if pestaña == limit_before:
        pestaña_text = limit_before
    elif pestaña == max_posts:
        pestaña_text = max_posts
    elif pestaña == max_comments:
        pestaña_text = max_comments

    for item in items:
        listbox.insert(tk.END, item)


note.pack()
note.mainloop()

I excpected something like with the prints. The problem is when I print, I have the same Key for all listbox

>>>limit_before
>>>50
>>>max_post
>>>60
>>>max_comments
>>>100
>>>max_post
>>>30

....

Martin Bouhier
  • 212
  • 2
  • 12

1 Answers1

0

Creating the variable pestaña_text is not handy in this case. It is defined in the main scope but it is overridden in the for loop and keeps the last value max_comments:

for pestaña, items in pestañas.items(): 
    ...
    if pestaña == limit_before:
        pestaña_text = limit_before
    elif pestaña == max_posts:
        pestaña_text = max_posts
    elif pestaña == max_comments:
        pestaña_text = max_comments

So when you call it next, in the the function mostrar_nombre, you will only get max_comments.

You can delete this for loop and use directly the selected tab text attribute by referring to the active tab of the NoteBook object with the method select:

def mostrar_nombre(event):
    listbox = event.widget
    index = listbox.curselection()
    value = listbox.get(index[0])
    print(note.tab(note.select(), "text"))
    print(value)

Some doc here and another similar question here.

PRMoureu
  • 12,817
  • 6
  • 38
  • 48