AttributeError: 'Demo1' object has no attribute 'textbox'

AttributeError: 'Demo1' object has no attribute 'textbox'

我正在从第一个 class(Demo1) 和调用函数 (fun1) 调用函数 ( fun1) 调用另一个 class(Demo2) 的另一个函数 (data) 到发送结果,但我在尝试在文本框中获取该结果时收到以下错误。我怀疑这是因为 class 自我冲突。你能帮我解决这个问题吗?

请查找代码:

from tkinter import ttk
import tkinter as tk
from tkinter import *


def fun1(self,name):
    result="check"
    Demo2.data(result)
    
def cal(master):
     master = Demo2(master)

class Demo1:
    
    def __init__(self, master):
        self.master = master

        button=tk.Button(self.master, text="check",anchor="w",command=lambda :fun1(self,"abc") )
        button.grid(row=0,column=1)
        button.config(command=lambda button=button: [cal(self.master),fun1(self,"abc")])
            
        
class Demo2:
    def __init__(self, master):
        self.master = master

        self.textbox=tk.Text(self.master,font=('Calibri',12))
        self.textbox.grid(row=0,column=1)
        

    def data(self,data):
        self.textbox.insert('end',data)


                            
def main():
    root = tk.Tk()
    app = Demo1(root)
    root.mainloop()


if __name__ == '__main__':
    main()        
 

 

错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Python\Python38\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "C:/Users/Desktop/New folder/demo/che.py", line 16, in <lambda>
    self.button=tk.Button(self.master, text="check",anchor="w",command=lambda :fun1(self,"abc") )
  File "C:/Users/Desktop/New folder/demo/che.py", line 8, in fun1
    Demo2.data(self,result)
  File "C:/Users/Desktop/New folder/demo/che.py", line 29, in data
    self.textbox.insert('end',data) #Error
AttributeError: 'Demo1' object has no attribute 'textbox'

在这里,您稍微修改一下您的代码:

from tkinter import ttk
import tkinter as tk
from tkinter import *


def fun1(parent, name):
    result = "check"
    master = Demo2(parent)
    master.data(result)


class Demo1:
    def __init__(self, master):
        self.master = master

        button = tk.Button(self.master, text="check", anchor="w", command=lambda: fun1(self.master, "abc"))
        button.grid(row=0, column=1)


class Demo2:
    def __init__(self, master):
        self.master = master

        self.textbox = tk.Text(self.master, font=('Calibri', 12))
        self.textbox.grid(row=0, column=1)

    def data(self, data):
        self.textbox.insert('end', data)


def main():
    root = tk.Tk()
    Demo1(root)
    root.mainloop()


if __name__ == '__main__':
    main()

此外,您没有在 fun1()

中使用名称