在Python中遍历YAML

I'm trying to build a Python application that has a Tkinter GUI. I got stuck there that I don’t understand how to literate through the read yaml string by keys. I want the values of field_names to be the names of the Entries in the code and the values of labels are the properties of labels text.

cfg.yml看起来像这样:
- field_name: neptun_code
  label: Neptun code
- field_name: result
  label: Result [%]
- field_name: mark
  label: Mark [1-5]
config.py看起来像这样:
from pathlib import Path


class Config(object):

    def __init__(self):
        self.document_yaml = None

    def function(self):
        self.from_yaml()

    def from_yaml(self):
        self.document_yaml = Path("./cfg.yaml").read_text()
        return self.document_yaml

Main.py The problem here is that I don’t know how to use the yaml list and how to iterate through it in def labels(self) and def entries(self)

import tkinter as tk
from tkinter import messagebox


class Window(object):

    def __init__(self):
        self.name = None
        self.window = None
        self.lbl = None
        self.txt = None


    def show(self):
        self.create_window()
        self.labels()
        self.entries()
        self.window.mainloop()

    def create_window(self):
        self.window = tk.Tk()
        self.window.title("MainWindow")
        self.window.geometry('350x200')

    def labels(self):
        # label
        row = 0
        for key, value in yaml_str: #?????
            self.lbl = tk.Label(self.window, text=value)
            self.lbl.grid(column=0, row=row)
            row += 1

    def entries(self):
        # entry
        row = 0
        for key, value in yaml_str: # ??????
            self.txt = tk.Entry(self.window, textvariable=self.name, width=20)
            self.txt.grid(column=1, row=row)
            row += 1



my_window = Window()
my_window.show()
评论