Home > Article > Backend Development > How to Pass Data Between Pages in a Tkinter Multi-Page Application?
Problem:
In a multi-page application using Tkinter, how can a class on one page access variable data stored in a class on a different page?
Leveraging Your Controller:
Assuming you're already utilizing a controller, you can exploit it for communication between pages.
Store a reference to the controller in each page:
<code class="python">class PageOne(ttk.Frame): def __init__(self, parent, controller): self.controller = controller ... class PageTwo(ttk.Frame): def __init__(self, parent, controller): self.controller = controller ...</code>
Create a method in the controller to retrieve a page based on its class name:
<code class="python">class MyApp(Tk): def get_page(self, classname): '''Returns an instance of a page given it's class name as a string''' for page in self.frames.values(): if str(page.__class__.__name__) == classname: return page return None</code>
In the page that needs to access the data, use the get_page method:
<code class="python">class PageTwo(ttk.Frame): def print_it(self): page_one = self.controller.get_page("PageOne") value = page_one.some_entry.get() print ('The value stored in StartPage some_entry = %s' % value)</code>
Storing Data in the Controller:
To reduce coupling between pages, consider storing the shared data in the controller.
Create a data structure in the controller to store the variables:
<code class="python">class MyApp(Tk): def __init__(self): ... self.app_data = {"name": StringVar(), "address": StringVar(), ... }</code>
Update the pages to reference the controller's data:
<code class="python">class PageOne(ttk.Frame): def __init__(self, parent, controller): self.controller=controller ... self.some_entry = ttk.Entry(self, textvariable=self.controller.app_data["name"], ...) </code>
Access the data from the controller:
<code class="python"> def print_it(self): value = self.controller.app_data["address"].get() ...</code>
The above is the detailed content of How to Pass Data Between Pages in a Tkinter Multi-Page Application?. For more information, please follow other related articles on the PHP Chinese website!