Skip to content Skip to sidebar Skip to footer

How To Save Shared Data In Tkinter For Python?

I'm very new to the world of GUIs with Python and attempting to build my first one with multiple pages, but sharing a variable from an entry box is really throwing me through a loo

Solution 1:

I guess problem is because frames are created in Keep.__init__, not when you run show_frame(), so PageTwo.__init__() is executed at start and text Welcome... is create at start - before you even see StartPage.

You should create empty label in __init__ and create text Welcome... in other method (ie. update_widgets()) which you will execute after show_frame() or event inside show_frame() if all classes will have update_widgets()>


Minimal working code:

import tkinter as tk


classKeep(tk.Tk):

    def__init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.shared_data ={
            "email": tk.StringVar(),
            "password": tk.StringVar()
        }

        self.frames = {
            'StartPage': StartPage(self, self),
            'PageTwo': PageTwo(self, self),
        }

        self.current_frame = None
        self.show_frame('StartPage')

    defshow_frame(self, name):
        if self.current_frame:
            self.current_frame.forget()
        self.current_frame = self.frames[name]
        self.current_frame.pack()

        self.current_frame.update_widgets() # <-- update data in widgetsclassStartPage(tk.Frame):

    def__init__(self, parent, controller):
        super().__init__(parent)
        self.controller = controller

        self.entry1 = tk.Entry(self, textvariable=self.controller.shared_data["email"])
        self.entry1.pack()
        entry2 = tk.Entry(self, show='*')
        entry2.pack()
        button = tk.Button(self, text="Submit", command=lambda:controller.show_frame("PageTwo"))
        button.pack()

    defupdate_widgets(self):
        passclassPageTwo(tk.Frame):

    def__init__(self, parent, controller):
        super().__init__(parent)
        self.controller = controller

        self.label = tk.Label(self, text="") # <-- create empty label
        self.label.pack()

    defupdate_widgets(self):
        self.label["text"] = "Welcome, {}".format(self.controller.shared_data["email"].get()) # <-- update text in labelif __name__ == "__main__":
    keep = Keep()
    keep.mainloop()

Post a Comment for "How To Save Shared Data In Tkinter For Python?"