WAMPS
WAMPS

Reputation: 349

Tkinter display dictionary key into text widget?

from tkinter import *

data = {'parakeet': ['fly', 'bird'], 'dog': 'animal', 'cat': 'feline'}
for key in data.keys():
    print(key)
root = Tk()
Label(root, text = "Enter your name").grid(row=0,ipadx = 10,ipady = 10)
Label(root, text = key ).grid(row=1,ipadx = 10,ipady = 100)

mainloop()

When I excute the code it only displays one key from the dictionary in the text widget. I want it to display all the keys.

Upvotes: 0

Views: 6028

Answers (2)

WAMPS
WAMPS

Reputation: 349

I got it myself in the end.I had to make a list of the keys and then append that lkst and print the list items

from tkinter import *
x = []
root = Tk()
data = {'parakeet': ['fly', 'bird'], 'dog': 'animal', 'cat': 'feline'}
for key in data.keys():
    x.append(key)

Label(root, text = "Enter your name").grid(row=0,ipadx = 10,ipady = 10)
Label(root, text = x ).grid(row=1,ipadx = 10,ipady = 50)

mainloop()

Upvotes: 1

Stef D'haeseleer
Stef D'haeseleer

Reputation: 66

from Tkinter import *

data = {'parakeet': ['fly', 'bird'], 'dog': 'animal', 'cat': 'feline'}

root = Tk()
Label(root, text = "Enter your name").grid(row=0,ipadx = 10,ipady = 10)

for i in range(len(data.keys())):
    key = data.keys()[i]
    print key
    Label(root, text = key ).grid(row=i + 1,ipadx = 10,ipady = 10)

mainloop()

This should solve your problem. First of all you should include the creation of the labels with the keys in the for loop for it to contain all the keys. And to prevent them from overlapping you have to change their row number while doing this. Also I changed the ipady to 10 (this is the vertical distance between your labels.

Feel free to ask any more questions if you have them!

Upvotes: 0

Related Questions