如何将变量值从一个文件中的一个类传递到另一个文件中的另一类

问题描述

我是python的新手。在python 3.7,Windows os上工作。假设我创建了一个名为 Class1.py 其中

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

现在我的 Class2.py 包含:

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

和我的 Main.py 包含:

import Class1
Class1.main_window.create()

显示错误是:root is not defined in Class2.py。我尝试过root = Class1.main_window.root来带来root的值,但是它显示错误,该函数没有属性root。

请帮助我解决问题。

解决方法

我认为函数需要扎根

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

然后在第1类:

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

第三:

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

首先,在Class2中您的类的名称“ this”中可能存在错误。 我猜“这”是当前对象实例的保留名称。 您应该将其更改为其他内容,例如“ class2”

然后,您应该在class1中实例化class2并将root作为参数传递给构造函数。只有这样,您才能在class2中使用root。

,

以下是将参数传递给类构造函数的示例:

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...