Skip to content Skip to sidebar Skip to footer

Use Variable In Different Class

I am a beginner in python. I have a problem with using variable in different class. Please help. Here is the sample code from Using buttons in Tkinter to navigate to different page

Solution 1:

You're defining the variable entry inside the body of a method, this does not make entry accessible to the global scope, this is how you should embed objects:

classPage1(Page):
   def__init__(self, *args, **kwargs):
       Page.__init__(self, *args, **kwargs)
       self.label = tk.Label(self, text="This is page 1")
       self.label.pack(side="top", fill="both", expand=True)

       self.entry = tk.Entry(self)
       self.entry.pack()

As you can see, you embed label and entry objects to self, the implied instance of class Page1 when you call class Page1(). Any variable assigned inside a body of a method or a function becomes local to that method or function. That's how you should go with your code.

Familiarize yourself with this concept: Short Description of Python Scoping Rules

Edit:

In class Page2 If you really want to access self.entry.get of class Page1, then you need to pass the object of class Page1 to the constructor of class Page2 and then fetch the entry from the object you passed to Page2.__init__ like the following:

classPage2(Page):
   def__init__(self, page1_obj, *args, **kwargs):
       Page.__init__(self, *args, **kwargs)
       self.label = tk.Label(self, text="This is page 2")
       self.label.pack(side="top", fill="both", expand=True)

       self.text = tk.Text(self, page1_obj.entry.get())  # access attributes of the passed-in object (page1._object)
       root.after(...)

Here you must pass an object to the constructor and then you'll be able to access the object's attributes including its bound methods. The reason why I did this though is because in your Page1 class you passed self to tk.Entry so I thought you probably wanted to use the returned results of self.entry = tk.Entry(self)of Page1. If you don't really intend to use the returned results of self.entry = tk.Entry(self) of Page1 class then you can add the same assignment in the constructor of Page2: self.entry = tk.Entry(self).

Post a Comment for "Use Variable In Different Class"