paulWich
paulWich

Reputation: 19

Executing a fuction while passing from a window to an other to get entry value

I want to get the text in the Entry field while passing from Page1 to Page2 and I want to pass it as a parameter to Page2 :

Here is my code

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()

How to make this please?

(sorry for my bad English)

Upvotes: 1

Views: 30

Answers (1)

Josselin
Josselin

Reputation: 2643

If you want the Page1 Entrybox content to be also available in Page2, your best option is to define and store the corresponding StringVar in Page1 and Page2's common controller instance:

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

Then you can access it as controller.v, in 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()

and Page2 as well:

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

Upvotes: 1

Related Questions