Search code examples
pythonpython-3.xtkinterpython-class

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


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.


Solution

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