
如何在多页面应用程序中的类之间访问变量数据
在多页面应用程序中,每个页面都由单独的类,访问类之间的变量数据可能具有挑战性。
利用控制器
一种方法是使用应用程序控制器类来促进页面之间的通信。将控制器的引用添加到每个页面的构造函数中:
1 2 3 4 | <code class = "python" > class PageOne(ttk.Frame):
def __init__(self, parent, controller):
self.controller = controller
...</code>
|
登录后复制
接下来,向控制器添加一个方法,该方法根据给定的类名检索页面实例:
1 2 3 4 5 6 7 | <code class = "python" > class MyApp(Tk):
...
def get_page(self, classname):
for page in self.frames.values():
if str(page. __class__ .__name__) == classname:
return page
return None</code>
|
登录后复制
然后,从在一个页面内,您可以访问另一页面的变量数据:
1 2 3 4 5 6 | <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>
|
登录后复制
在控制器中存储数据
为了避免页面之间的紧密耦合,请考虑将数据存储在控制器中控制器而不是在特定页面中:
1 2 3 4 5 6 7 | <code class = "python" > class MyApp(Tk):
def __init__(self):
...
self.app_data = { "name" : StringVar(),
"address" : StringVar(),
...
}</code>
|
登录后复制
然后,在每个页面内,创建小部件时引用控制器的数据结构:
1 2 3 4 5 6 | <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>
|
登录后复制
最后,直接从控制器访问数据:
1 2 3 | <code class = "python" > def print_it(self):
value = self.controller.app_data[ "address" ].get()
...</code>
|
登录后复制
以上是如何在多页面应用程序中的类之间共享数据?的详细内容。更多信息请关注PHP中文网其他相关文章!