Use variable in different class [duplicate]

2024/7/7 6:17:10

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 pages of the application?

import Tkinter as tkclass Page(tk.Frame):def __init__(self, *args, **kwargs):tk.Frame.__init__(self, *args, **kwargs)def show(self):self.lift()class Page1(Page):def __init__(self, *args, **kwargs):Page.__init__(self, *args, **kwargs)label = tk.Label(self, text="This is page 1")label.pack(side="top", fill="both", expand=True)entry = tk.Entry(self)entry.pack()class Page2(Page):def __init__(self, *args, **kwargs):Page.__init__(self, *args, **kwargs)label = tk.Label(self, text="This is page 2")label.pack(side="top", fill="both", expand=True)text = tk.Text(self, entry.get())root.after(...)class MainView(tk.Frame):def __init__(self, *args, **kwargs):tk.Frame.__init__(self, *args, **kwargs)p1 = Page1(self)p2 = Page2(self)buttonframe = tk.Frame(self)container = tk.Frame(self)buttonframe.pack(side="top", fill="x", expand=False)container.pack(side="top", fill="both", expand=True)p1.place(in_=container, x=0, y=0, relwidth=1, relheight=1)p2.place(in_=container, x=0, y=0, relwidth=1, relheight=1)b1 = tk.Button(buttonframe, text="Page 1", command=p1.lift)b2 = tk.Button(buttonframe, text="Page 2", command=p2.lift)b1.pack(side="left")b2.pack(side="left")p1.show()if __name__ == "__main__":root = tk.Tk()main = MainView(root)main.pack(side="top", fill="both", expand=True)root.wm_geometry("400x400")root.mainloop()

Then it have two problems:

 NameError: global name 'entry' is not definedNameError: global name 'root' is not defined

How can i use these variable? Please help!

Answer

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:

class Page1(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:

class Page2(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).

https://en.xdnf.cn/q/120219.html

Related Q&A

Embedded function returns None

My function returns None. I have checked to make sure all the operations are correct, and that I have a return statement for each function.def parameter_function(principal, annual_interest_rate, durati…

calculate days between several dates in python

I have a file with a thousand lines. Theres 12 different dates in a single row. Im looking for two conditions. First: It should analyze row by row. For every row, it should check only for the dates bet…

Appeding different list values to dictionary in python

I have three lists containing different pattern of values. This should append specific values only inside a single dictionary based on some if condition.I have tried the following way to do so but i go…

Split only part of list in python

I have a list[Paris, 458 boulevard Saint-Germain, Marseille, 29 rue Camille Desmoulins, Marseille, 1 chemin des Aubagnens]i want split after keyword "boulevard, rue, chemin" like in output[Sa…

How to find the index of the element in a list that first appears in another given list?

a = [3, 4, 2, 1, 7, 6, 5] b = [4, 6]The answer should be 1. Because in a, 4 appears first in list b, and its index is 1.The question is that is there any fast code in python to achieve this?PS: Actual…

How to yield fragment URLs in scrapy using Selenium?

from my poor knowledge about webscraping Ive come about to find a very complex issue for me, that I will try to explain the best I can (hence Im opened to suggestions or edits in my post).I started usi…

Django Database Migration

Hi have a django project a full project now I want to migrate to mysql from the default Sqlite3 which is the default database. I am on a Mac OS and I dont know how to achieve this process. Any one wit…

Search engine using python for bookmarked sites [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 1…

How to extract only particular set of structs from a file between braces in python

a. Have a scenario, where in my function reads in a file which contains list of c-structures as shown below, reads the file and extracts all the information between { } braces for each structure and st…

Selection of Face of a STL by Face Normal value Threshold

I want to write a script in Python which can generate facegroups in a STL as per the Face Normal value condition. For example, Provided is the snap of Stl, Different colour signifies the face group con…