0

我是 python 新手。使用 python 3.7,Windows 操作系统。假设我创建了一个名为 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 的错误。

请帮我解决我的问题。

4

3 回答 3

1

我认为功能需要获得根

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

然后在class1中:

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

第三:

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

===

类1.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()

类2.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()
于 2020-10-06T07:59:38.157 回答
0

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

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

于 2020-10-06T07:57:07.247 回答
0

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

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()
于 2020-10-06T08:31:26.567 回答