打印值并键入所有ListBox TKinter

时间:2019-07-19 16:03:56

标签: python python-3.x tkinter

当我打印每个列表的值时,我无法打印dic的键值

我尝试着写下的代码!

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

我对版画很满意。问题是当我打印时,所有列表框的键都相同

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

....

1 个答案:

答案 0 :(得分:0)

在这种情况下,创建变量pestaña_text并不方便。它在主作用域中定义,但在for循环中被覆盖,并保留最后一个值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

因此,当您下次调用它时,在函数mostrar_nombre中,您只会得到max_comments

您可以删除此for循环并通过使用方法text引用NoteBook对象的活动标签来直接使用选定的标签select属性:

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

一些文档here和另一个类似的问题here