保存并加载GUI-tkinter [英] Save and Load GUI-tkinter

查看:163
本文介绍了保存并加载GUI-tkinter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想保存并加载我的GUI.

I want to save and load my GUI.

我已经制作了一个GUI,当我单击保存"按钮时,我想要它.

I have made a GUI and I want that when I click on the save button.

它应该将GUI保存在一些数据中,当我单击加载按钮时,它将再次加载相同的GUI.

It should save the GUI in some blob of data and when I click on load button then it will load the same GUI again.

我的GUI有各种文本小部件,在选项菜单"下拉菜单中. 我是python的新手,所以有人可以帮助我吗?

My GUI has various text widgets, drop down Option Menu. I am new to python, so someone can help me on this, please?

我也尝试了泡菜模块.

I have tried pickle module, too.

推荐答案

如果不自己做,就无法做自己想做的事情.您需要编写一个函数,该函数将收集所需的所有数据以还原GUI,然后可以将其保存到磁盘.然后,在GUI启动时,您可以读取数据并重新配置小部件以包含此数据.

You can't do what you want to do without doing the work yourself. You'll need to write a function that gathers all the data you need in order to restore the GUI, and then you can save that to disk. Then, when the GUI starts up you can read the data and reconfigure the widgets to contain this data.

Tkinter为您提供了完成它所需的几乎所有内容,但是您必须自己完成所有工作.腌制GUI无效.

Tkinter gives you pretty much everything you need in order to accomplish it, but you have to do all the work yourself. Pickling the GUI won't work.

这是一个人为的例子.在弹出的窗口中输入一些表达式.请注意,它们已添加到组合框中.退出时,当前表达式,保存的表达式和当前值都将被保存.下次启动GUI时,将恢复这些值.

Here's a contrived example. Enter a few expressions in the window that pops up. Notice that they are added to the combobox. When you exit, the current expression, the saved expressions, and the current value are all saved. The next time you start the GUI, these values will be restored.

try:
    import Tkinter as tk
    import ttk
except ModuleNotFoundError:
    import tkinter as tk
    import tkinter.ttk as ttk
import pickle

FILENAME = "save.pickle"


class Example(tk.Frame):
    def __init__(self, parent):
        self.create_widgets(parent)
        self.restore_state()

    def create_widgets(self, parent):
        tk.Frame.__init__(self, parent, borderwidth=9, relief="flat")

        self.previous_values = []

        l1 = tk.Label(self, text="Enter a mathematical expression:", anchor="w")
        l2 = tk.Label(self, text="Result:", anchor="w")
        self.expressionVar = tk.StringVar()
        self.expressionEntry = ttk.Combobox(self, textvariable=self.expressionVar, values=("No recent values",))
        self.resultLabel = tk.Label(self, borderwidth=2, relief="groove", width=1)
        self.goButton = tk.Button(self, text="Calculate!", command=self.calculate)

        l1.pack(side="top", fill="x")
        self.expressionEntry.pack(side="top", fill="x", padx=(12, 0))
        l2.pack(side="top", fill="x")
        self.resultLabel.pack(side="top", fill="x", padx=(12, 0), pady=4)
        self.goButton.pack(side="bottom", anchor="e", pady=4)

        self.expressionEntry.bind("<Return>", self.calculate)

        # this binding saves the state of the GUI, so it can be restored later
        root.wm_protocol("WM_DELETE_WINDOW", self.save_state)

    def calculate(self, event=None):
        expression = self.expressionVar.get()
        try:
            result = "%s = %s" % (expression, eval(expression))
            self.previous_values.append(expression)
            self.previous_values = self.previous_values[-8:]
            self.expressionVar.set("")
            self.expressionEntry.configure(values=self.previous_values)

        except:
            result = "invalid expression"

        self.resultLabel.configure(text=str(result))

    def save_state(self):
        try:
            data = {
                "previous": self.previous_values,
                "expression": self.expressionVar.get(),
                "result": self.resultLabel.cget("text"),
            }
            with open(FILENAME, "wb") as f:
                pickle.dump(data, f)

        except Exception as e:
            print
            "error saving state:", str(e)

        root.destroy()

    def restore_state(self):
        try:
            with open(FILENAME, "rb") as f:
                data = pickle.load(f)
            self.previous_values = data["previous"]
            self.expressionEntry.configure(values=self.previous_values)
            self.expressionVar.set(data["expression"])
            self.resultLabel.configure(text=data["result"])
        except Exception as e:
            print
            "error loading saved state:", str(e)


if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

这篇关于保存并加载GUI-tkinter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆