When accessing data from other pages in tkinter, it's essential to have a reference to the specific page you're targeting. In your case, PageTwo needs to retrieve the self.v variable from PageOne.
Tkinter provides a simple mechanism for this. Add a self.controller attribute to each page's constructor, which gives access to the controller object. The controller holds references to all pages, enabling you to retrieve any page's reference.
Add the following line to each page's constructor to establish the self.controller attribute:
self.controller = controller
Next, add a get_page method to the SampleApp class to retrieve page references:
class SampleApp(tk.Tk): ... def get_page(self, page_class): return self.frames[page_class] ...
Now, within any page, you can access another page's object using the controller's get_page method. For instance, in PageTwo, you can access PageOne's v variable as follows:
page1 = self.controller.get_page(PageOne) page1.v.set("Hello, world")
A more elegant solution is to create shared data that all pages can access. Initialize a dictionary in the SampleApp class and grant each page access through the controller:
class SampleApp(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.shared_data = { "username": tk.StringVar(), "password": tk.StringVar(), ... }
Pages can then access the shared data via the controller:
entry1 = tk.Entry(self, textvariable=self.controller.shared_data["username"]) username = self.controller.shared_data["username"].get()
Utilizing shared data promotes loose coupling, making page modifications easier without affecting other pages. The controller serves as a central point of reference, reducing the dependency among pages.
The above is the detailed content of How to Share Data Between Different Classes in a Tkinter Application?. For more information, please follow other related articles on the PHP Chinese website!