如何从类中获取变量数据?
- 2025-01-07 08:44:00
- admin 原创
- 108
问题描述:
这是一个较长应用程序的简化示例,其中我有多页小部件用于收集用户输入的信息。MyApp
将每个页面实例化为一个类。 在示例中,PageTwo
我想打印 的值,StringVar
它将来自 Entry 小部件的数据存储在 中PageOne
。
我该怎么做?我每次尝试都以这样或那样的异常告终。
from tkinter import *
from tkinter import ttk
class MyApp(Tk):
def __init__(self):
Tk.__init__(self)
container = ttk.Frame(self)
container.pack(side="top", fill="both", expand = True)
self.frames = {}
for F in (PageOne, PageTwo):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky = NSEW)
self.show_frame(PageOne)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class PageOne(ttk.Frame):
def __init__(self, parent, controller):
ttk.Frame.__init__(self, parent)
ttk.Label(self, text='PageOne').grid(padx=(20,20), pady=(20,20))
self.make_widget(controller)
def make_widget(self, controller):
self.some_input = StringVar
self.some_entry = ttk.Entry(self, textvariable=self.some_input, width=8)
self.some_entry.grid()
button1 = ttk.Button(self, text='Next Page',
command=lambda: controller.show_frame(PageTwo))
button1.grid()
class PageTwo(ttk.Frame):
def __init__(self, parent, controller):
ttk.Frame.__init__(self, parent)
ttk.Label(self, text='PageTwo').grid(padx=(20,20), pady=(20,20))
button1 = ttk.Button(self, text='Previous Page',
command=lambda: controller.show_frame(PageOne))
button1.grid()
button2 = ttk.Button(self, text='press to print', command=self.print_it)
button2.grid()
def print_it(self):
print ('The value stored in StartPage some_entry = ')#What do I put here
#to print the value of some_input from PageOne
app = MyApp()
app.title('Multi-Page Test App')
app.mainloop()
解决方案 1:
利用你的控制器
假设您已经了解了控制器的概念(即使您没有使用它),您可以使用它在页面之间进行通信。第一步是在每个页面中保存对控制器的引用:
class PageOne(ttk.Frame):
def __init__(self, parent, controller):
self.controller = controller
...
class PageTwo(ttk.Frame):
def __init__(self, parent, controller):
self.controller = controller
...
接下来,向控制器添加一个方法,该方法将在给定类名或其他标识属性时返回页面。对于您的情况,由于您的页面没有任何内部名称,因此您只需使用类名即可:
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
注意:上述实现基于问题中的代码。问题中的代码源自 stackoverflow 上的另一个答案。此代码与原始代码在管理控制器中的页面的方式上略有不同。它使用类引用作为键,而原始答案使用类名。
有了这些,任何页面都可以通过调用该函数来获取对任何其他页面的引用。然后,通过对该页面的引用,您可以访问该页面的公共成员:
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)
在控制器中存储数据
直接从一个页面访问另一个页面并不是唯一的解决方案。缺点是您的页面紧密耦合。很难在一个页面中进行更改而不在一个或多个其他类中进行相应的更改。
如果您的所有页面都设计为协同工作以定义一组数据,那么将数据存储在控制器中可能是明智之举,这样任何给定的页面都不需要知道其他页面的内部设计。这些页面可以自由地以它们想要的方式实现小部件,而不必担心哪些其他页面可能会访问这些小部件。
例如,您可以在控制器中有一个字典(或数据库),每个页面负责用其数据子集更新该字典。然后,您可以随时向控制器索要数据。实际上,页面正在签订合同,承诺使其全局数据子集与 GUI 中的内容保持同步。只要您遵守合同,您就可以在页面实现中做任何您想做的事情。
为此,控制器将在创建页面之前创建数据结构。由于我们使用 tkinter,因此该数据结构可以由StringVar
其他 Var 类的实例或任何其他 Var 类组成。不一定非要这样,但在这个简单的示例中这样做很方便、简单:
class MyApp(Tk):
def __init__(self):
...
self.app_data = {"name": StringVar(),
"address": StringVar(),
...
}
接下来,修改每个页面以在创建小部件时引用控制器:
class PageOne(ttk.Frame):
def __init__(self, parent, controller):
self.controller=controller
...
self.some_entry = ttk.Entry(self,
textvariable=self.controller.app_data["name"], ...)
最后,您可以从控制器而不是页面访问数据。您可以丢弃get_page
,并像这样打印值:
def print_it(self):
value = self.controller.app_data["address"].get()
...
解决方案 2:
我面临的挑战是知道将 print_it 函数放在哪里。我添加了以下内容使其工作,尽管我不太明白为什么要使用它们。
def show_frame(self,page_name):
...
frame.update()
frame.event_generate("<<show_frame>>")
并添加了 show_frame.bind
class PageTwo(tk.Frame):
def __init__(....):
....
self.bind("<<show_frame>>", self.print_it)
...
def print_it(self,event):
...
如果没有上述添加,当执行主循环时,Page_Two[frame[print_it()]] print_it 函数会在 PageTwo 可见之前执行。
try:
import tkinter as tk # python3
from tkinter import font as tkfont
except ImportError:
import Tkinter as tk #python2
import tkFont as tkfont
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title_font = tkfont.Font(family="Helvetica", size=18, weight="bold", slant="italic")
# data Dictionary
self.app_data = {"name": tk.StringVar(),
"address": tk.StringVar()}
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others.
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0,weight=1)
self.frames = {}
for F in (StartPage, PageOne, PageTwo):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("StartPage")
def show_frame(self, page_name):
''' Show a frame for the given page name '''
frame = self.frames[page_name]
frame.tkraise()
frame.update()
frame.event_generate("<<show_frame>>")
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="this is the start page", font=self.controller.title_font)
label.pack(side="top", fill="x", pady=10)
# Update the Name value only
self.entry1 = tk.Entry(self,text="Entry", textvariable=self.controller.app_data["name"])
self.entry1.pack()
button1 = tk.Button(self, text="go to page one", command = lambda: self.controller.show_frame("PageOne")).pack()
button2 = tk.Button(self, text="Go to page Two", command = lambda: self.controller.show_frame("PageTwo")).pack()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 1", font=self.controller.title_font)
label.pack(side="top", fill="x", pady=10)
# Update the Address value only
self.entry1 = tk.Entry(self,text="Entry", textvariable=self.controller.app_data["address"])
self.entry1.pack()
button = tk.Button(self, text="Go to the start page", command=lambda: self.controller.show_frame("StartPage"))
button.pack()
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
# Bind the print_it() function to this Frame so that when the Frame becomes visible print_it() is called.
self.bind("<<show_frame>>", self.print_it)
label = tk.Label(self, text="This is page 2", font=self.controller.title_font)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: self.controller.show_frame("StartPage"))
button.pack()
def print_it(self,event):
StartPage_value = self.controller.app_data["name"].get()
print(f"The value set from StartPage is {StartPage_value}")
PageOne_value= self.controller.app_data["address"].get()
print(f"The value set from StartPage is {PageOne_value}")
if __name__ == "__main__":
app = SampleApp()
app.mainloop()