使用标签Tkinter Python在新的Windows GUI中显示所有dict



我是Python的新手,尽管在线培训很少。我无法与以下问题相关。

我正在使用tkinter gui

from Tkinter import *
root = Tk()
trainings = {"title":"Python Training Course for Beginners",
                     "location":"Frankfurt",
                     "ID": 111,"title":"Intermediate Python Training",
                     "location":"Berlin",
                     "ID": 133,"title":"Python Text Processing Course",
                     "location":"Mdsgtd",
                     "ID": 122}
  for key in trainings.keys():
   x = trainings.get(key)
   print x

  Label(root, text = x ).pack()
  mainloop()

仅获取输出:122

,但我期望将结果显示在GUI标签中:

{'ID': 111, 'location': 'Frankfurt', 'title': 'Python Training Course for Beginners'}
{'ID': 122, 'location': 'Mdsgtd', 'title': 'Python Text Processing Course'}
{'ID': 133, 'location': 'Berlin', 'title': 'Intermediate Python Training'}

我可以在函数标签中使用以下代码中的标签:

不起作用:
def OnButtonClick(self):
    self.top= Toplevel()
    self.top.title("Read Data Service Menu Item")
    self.topdata = {'parakeet': ['fly', 'bird'], 'dog': 'animal', 'cat': 'feline'}
    for key in self.topdata.keys():
               x = self.topdata.get(key)
    self.topL2 = Label(self.top, text = key).pack()
    self.top.resizable(1,0)
    self.top.transient(self)
    self.B1.config(state = 'normal') #disable/normal
    self.topButton = Button(self.top, text = 'Close', command = self.OnChildClose)
    self.topButton.pack()

您目前有一些问题,如评论中所述。首先,您应该将trainings字典更改为字典列表让您依次存储每个课程的相关信息。

假设您想显示与每个课程有关的信息的不同标签,则应有效:

from Tkinter import *
courses = [{"title": "Python Training Course for Beginners",
            "location": "Frankfurt",
            "ID": 111},
           {"title": "Intermediate Python Training",
            "location": "Berlin",
            "ID": 133},
           {"title": "Python Text Processing Course",
            "location": "Mdsgtd",
            "ID": 122}]

root = Tk()
for course in courses:
    temp_text = '{0} ({1}) - {2}'.format(course['title'], course['ID'], course['location'])
    Label(root, text=temp_text).pack()
mainloop()

我们使用字符串格式来创建一个写得很好的输出,课程名称,然后在括号中ID,然后在dash之后的课程位置。

这里至关重要的是我们要为每门课程创建一个Label小部件 - 因此,我们在我们的循环中添加新的Label以确保发生这种情况。

最新更新