How to pass variable value from one class in one file to another class in another file python tkinter

444 views Asked by At

I am new to python. working on python 3.7, windows os. suppose that i have created a file named Class1.py in which

import tkinter as tk
import Class2
class main_window:
    def openanotherwin():
        Class2.this.now()
    def create():
        root = tk.Tk()
        button1 = tk.Button(root, text="Open another window", command = openanotherwin )
        button1.pack()
        root.mainloop()

Now my Class2.py contains:

import tkinter as tk
class this():
    def now():
        new = tk.Toplevel(root)  #Error displayed: root is not defined
        lb = tk.Label(new, text = "Hello")
        lb.pack()
        new.mainloop()

and my Main.py contains:

import Class1
Class1.main_window.create()

Error displayed is: root is not defined in Class2.py. I have tried root = Class1.main_window.root to bring the value of root but it showed error that function has no attribute root.

Please help me solving my problem.

3

There are 3 answers

2
Timur U On BEST ANSWER

I think function need to get root

 def now(root): 
    new = tk.Toplevel(root)  #Error displayed: root is not defined

Then in class1:

def openanotherwin(root):
    Class2.this.now(root)

And third:

button1 = tk.Button(root, text="Open another window", command=lambda: main_window.openanotherwin(root) )

===

Class1.py

import tkinter as tk
import Class2
class main_window:
def openanotherwin(root):
    Class2.this.now(root)
    def create():
        root = tk.Tk()
button1 = tk.Button(root, text="Open another window", command=lambda: main_window.openanotherwin(root) )
        button1.pack()
        root.mainloop()

Class2.py

import tkinter as tk
class this():
def now(root): 
    new = tk.Toplevel(root)  #Error displayed: root is not defined
        lb = tk.Label(new, text = "Hello")
        lb.pack()
        new.mainloop()
0
Marcel Hell On

Here's an example for passing arguments to a class constructor:

class DemoClass:
    num = 101

    # parameterized constructor
    def __init__(self, data):
        self.num = data

    # a method
    def read_number(self):
        print(self.num)


# creating object of the class
# this will invoke parameterized constructor
obj = DemoClass(55)

# calling the instance method using the object obj
obj.read_number()

# creating another object of the class
obj2 = DemoClass(66)

# calling the instance method using the object obj
obj2.read_number()
3
Marcel Hell On

First, an error might be in the name "this" of your class in Class2. I guess that "this" is a reserved name for the current object instance. You should change that to something else, e.g. "class2"

Then you should instantiate class2 in your class1 and pass root to the constructor as an argument. Only then, you can use root in class2.