【问题标题】:Print value and key in all ListBox TKinter在所有 ListBox TKinter 中打印值和键
【发布时间】:2019-11-28 15:53:21
【问题描述】:

打印每个列表的值时无法打印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

....

【问题讨论】:

    标签: python python-3.x tkinter


    【解决方案1】:

    在这种情况下,创建变量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属性,通过select方法引用NoteBook对象的活动标签:

    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

    【讨论】:

      猜你喜欢
      • 2012-02-13
      • 2020-05-24
      • 2018-05-16
      • 2019-02-10
      • 2014-05-04
      • 2018-04-23
      • 2013-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多