用户更改窗口小部件中的选项时如何更新配置文件?

时间:2020-08-09 18:22:45

标签: python tkinter

我正在创建GUI脚本,以便由用户创建配置文件。现在的问题是,当用户更改选项时,文件不会更新。我的目标是用户可以为其配置文件选择值。

我该如何解决这个问题?

import tkinter as tk

class ConfigFile:
   def __init__(self, file):
       self.file = file
       f = open(self.file, 'w')
       f.write('[\n')
       f.write("   {\n")
       f.close()

   def write_line(self, line):
       with open(self.file, 'a') as out:
           out.write(line)
           out.close()


class AppGui(tk.Frame):
    def __init__(self, parent):
        super(AppGui, self).__init__(parent)
        file = ConfigFile("configfile.json")
        self.content_type(file)
        self.output_directory(file)
        self.source_type(file)
        self.raw_source_path()
        self.id_field(file)
        self.search_index()

    def content_type(self, file):
        global window
        optionList = ["ITEM",
                      "USER",
                      "RATING"]
        variable = tk.StringVar(window)
        variable.set(optionList[0])
        opt = tk.OptionMenu(window, variable, *optionList)
        opt.configure(width=90, font=('Helvetica', 12))
        opt.pack(side="top")
        labelTest = tk.Label(window, text="", font=('Helvetica', 12), fg='green')
        labelTest.pack(side="top")

        def callback(*args):
            labelTest.configure(text="The selected content type is {}".format(variable.get()))

        variable.trace("w", callback)
        line = '   "content_type": "{}",\n'.format(variable.get())
        file.write_line(line)


if __name__ == "__main__":
    window = tk.Tk()
    window.title("Orange_cb_recsys")
    frame = tk.Frame(bg="grey")
    appUI = AppGui(frame)
    appUI.pack(fill="both", expand=True)
    window.mainloop()

0 个答案:

没有答案