引用How to get variable data from a class
为了方便起见,上述帖子中的代码以合并形式在底部重复。
此代码将 Frame PageOne 中输入的变量传递给 PageTwo,按下按钮时,该变量将打印到控制台。
没有成功,我一直尝试设置PageTwo的标签以显示在PageOne上输入的变量。最初,我希望代码修改能像这样简单:
class PageTwo(ttk.Frame):
def __init__(self, parent, controller):
self.controller=controller
ttk.Frame.__init__(self, parent)
ttk.Label(self, text='PageTwo').grid(padx=(20,20), pady=(20,20))
...
将最后一行更改为:
ttk.Label(self, text=self.controller.app_data["name"].get()).grid(padx=(20,20), pady=(20,20))
我已经使用不同帖子的想法尝试了各种组合,但似乎我缺少一些基本推理。这位新手将非常感谢任何帮助。
从上面引用的帖子中合并的完整代码:
#!/usr/bin/python
from Tkinter import *
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 = {}
self.app_data = {"name": StringVar(),
"address": StringVar()
}
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):
self.controller=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.controller.app_data["name"], 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):
self.controller=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):
value = self.controller.app_data["name"].get()
print "The value stored in StartPage some_entry = ",value
app = MyApp()
app.title('Multi-Page Test App')
app.mainloop()
最佳答案
正如Figbeam提到的,当你切换框架时它已经被创建了。我进行了编辑以在按下按钮时更新标签。
class PageTwo(ttk.Frame):
def __init__(self, parent, controller):
self.controller=controller
ttk.Frame.__init__(self, parent)
self.label = ttk.Label(self, text='PageOne')
self.label.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):
value = self.controller.app_data["name"].get()
print ("The value stored in StartPage some_entry = %s", value)
self.label['text'] = value
或者,您可以在第二页中为标签使用相同的字符串 var:
ttk.Label(self, textvariable=self.controller.app_data["name"]).grid(padx=(20,20), pady=(20,20))
关于python - Tkinter:从一帧获取变量以在另一帧中显示为标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50229411/