从窗口传递到另一个窗口时执行功能以获取条目值

时间:2017-05-15 08:56:49

标签: python-3.x tkinter

我想在从Page1传递到Page2时在Entry字段中获取文本,并且我想将它作为参数传递给Page2:

这是我的代码

import tkinter as tk

class MyApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        container = tk.Frame(self)
        container.pack(side = "top", fill = "both", expand = True)
        self.frames ={}
        for f in  (Page1, Page2):
            frame = f(container,self)
            self.frames[f] = frame
            frame.grid(row = 1000, column = 500, sticky = "nsew")
        self.show_frame(Page1)

    def show_frame(self,cont):
        frame = self.frames[cont]
        frame.tkraise()


class Page1(tk.Frame):
    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)
        Frame0 = tk.Frame(self)
        Frame0.pack()
        Frame1 = tk.Frame(self)
        Frame1.pack()
        tk.Label(Frame0,text = "Page 1").pack()
        v = tk.StringVar()
        def say_hello():
            print(v.get())
        e = tk.Entry(Frame0, textvariable = v).pack()
        tk.Button(Frame1,text = "Page 2", command = (lambda: controller.show_frame(Page2))and say_hello).pack()

class Page2(tk.Frame) :
    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)
        Frame0 = tk.Frame(self)
        Frame0.pack()
        Frame1 = tk.Frame(self)
        Frame1.pack()
        tk.Label(Frame0, text="Page 2").pack()
        tk.Button(Frame1,text = "Page 1", command = (lambda: controller.show_frame(Page1))).pack()

app = MyApp()
app.mainloop()

如何做到这一点?

(抱歉我的英语不好)

1 个答案:

答案 0 :(得分:1)

如果您希望Page1中的Page2条目箱内容也可用,那么您最好的选择是在Page1Page2中定义和存储相应的StringVar公共控制器实例:

class MyApp(tk.Tk):
    def __init__(self):
        ...
        # Store the StringVar in MyApp's instance
        self.v = tk.StringVar()
        ...

然后,您可以controller.v中的Page1访问它:

class Page1(tk.Frame):
    def __init__(self,parent,controller):
        ...
        tk.Entry(Frame0, textvariable = controller.v).pack()
        tk.Button(Frame1,text = "Page 2", 
                  command=lambda: controller.show_frame(Page2)).pack()

Page2

class Page2(tk.Frame) :
    def __init__(self,parent,controller):
        ...
        tk.Button(Frame0, text="Print Entry Value", 
                  command=lambda: print(controller.v.get())).pack()