Question

I need to display a python dictionary in ttk. So currently the user inputs values and those are stored in a dictionary, after each entry the dictionary will update with the new value. I want to print these values in a nice neat vertical column. Updating the new value at the bottom of the column each time the user inputs.

I am aware of this method, but don't know how to map it to TK:

>>> D = {'d1': {'a':'1'}, 'd2': {'b':'2'}, 'd3': {'c':'3'}}
>>> for k, d in D.items():
    print k, d

d2 {'b': '2'}
d3 {'c': '3'}
d1 {'a': '1'}

Problem with this is if I set the "print k, d" to my TTK label widget it is just going to update the widget each time it goes through essentially only displaying the last variable it runs through.

So how would I get it to display a dictionary with each value/key on a new line and not "forget" the previous value when it updates?

Was it helpful?

Solution

Make a string. Then set it as the text of the label.

For example:

from Tkinter import *   # Python 3.x: from tkinter import *
from ttk import *       # Python 3.x: from tkinter.ttk import *

D = {'d1': {'a':'1'}, 'd2': {'b':'2'}, 'd3': {'c':'3'}}

root = Tk()
lb = Label(root, text='')
lb['text'] = '\n'.join('{} {}'.format(k, d) for k, d in D.items()) # <---
# OR lb.config(text=....)
# OR lb.configure(text=...)
lb.pack()
root.mainloop()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top