【问题标题】:Propagate a dict in a Listbox of tkinter在 tkinter 的列表框中传播 dict
【发布时间】:2020-10-23 12:25:09
【问题描述】:

我在 tkinter 列表框小部件中列出了字典 {'337':'Anderson','47':'Stuttgart' ...}。那对我有用。使用 curselection(),我还可以通过双击获取像“Anderson”这样的值。

我的功能如下:

def select_xml(event):
    widget = event.widget
    selection = widget.curselection()
    value = widget.get(selection[0])
    print (value)

这个打印例如安德森。

问题:我的 dict 的键是否丢失,或者如何检索我选择的值的键。我找不到任何关于 dict 和 Listbox 的信息。

【问题讨论】:

  • 创建字典{'Anderson': '337', 'Stuttgart':'47' ...},然后你可以使用Anderson作为键找到值337

标签: python dictionary tkinter listbox


【解决方案1】:

我不知道您是如何创建 Listbox 但您可以将您的列表转换为

{'Anderson': '337', 'Stuttgart':'47' ...}

然后使用Anderson作为键获取337

data = {'337':'Anderson', '47':'Stuttgart'}

data2 = {val:key for key,val in data.items()}

print(data2)

print(data2['Anderson'])

如果您在 dict 中多次使用相同的名称,则转换可能会删除一些值,然后使用 list/dict 理解更好地过滤原始 dict

keys = [key for key,val in data.items() if val == 'Anderson']

print(keys)

但是,如果您多次使用相同的名称,那么您会得到很多键,您将不知道该选择哪一个。最好使用 (key,values) 创建列表,然后使用 selection[0] 作为此列表中的索引

data = {'337':'Anderson', '47':'Stuttgart'}

data2 = [(key, val) for key,val in data.items()]

selection = [0]

print( data2[ selection[0] ] )

最少的工作代码

import tkinter as tk
        
# --- functions ---

def on_click(event):
    widget = event.widget
    sel = widget.curselection()
    val = widget.get(sel[0])
    
    print('dict2:', dict2[val])
    print('list2:', list2[sel[0]])
    print('---')

# --- main ---

data = {'337': 'Anderson', '47': 'Stuttgart'}

dict2 = {val:key for key, val in data.items()}
list2 = list(data.items())

root = tk.Tk()

listbox = tk.Listbox(root)
listbox.pack()

listbox.insert('end', *data.values())
listbox.bind('<Double-Button-1>', on_click)
             
root.mainloop()   

结果:

dict2: 47
list2: ('47', 'Stuttgart')
---
dict2: 337
list2: ('337', 'Anderson')
---

【讨论】:

  • 谢谢。这正是我搜索的内容。
猜你喜欢
  • 2017-12-21
  • 2012-01-28
  • 1970-01-01
  • 2017-12-11
  • 1970-01-01
  • 2021-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多