Tkinter 自定义文本框 class 不能使用 def

Tkinter custom textbox class can't use def

我可能忽略了一些明显的东西,但这个问题让我 运行 陷入困境。 我想弹出多个文本框并即时填充每个文本框。当我 运行 以下代码时,我得到一个“AttributeError”,出于某种原因,它希望我在 def.

中为“self”提供一些东西

我的根本错误在哪里? 以下是包含在单独文件中的Class。

class NoninteractiveTextBox:
def __init__(self, master, location, sizew, sizeh):
    self.text_box = Text(master, width=sizew, height=sizeh, font=("Helvetica", 16))
    self.text_box.tag_configure("center", justify="center")
    self.text_box.place(x=location[0], y=location[1])
    self.text_box.tag_add("center", "1.0", "end")
    self.text_box.config(state="disabled")

def inject_text(self, event_text):
    self.text_box.config(state="normal")
    self.text_box.insert(1.0, event_text)
    self.text_box.tag_add("center", "1.0", "end")
    self.text_box.config(state="disabled")

以下基本是主要的

from tkinter import *
from WidgetsTools import NoninteractiveTextBox

root = Tk()
root.title('test text')
root.geometry("1600x900")

location = [100, 500]
ntb = NoninteractiveTextBox
ntb(root, location, 80, 10)
ntb.inject_text(???, "testing text for NTB")


root.mainloop()

ntb.inject_text(???, “NTB 测试文本”) 是问题所在,我想这是我制作 class 本身的方式中的新手错误。任何提示都会有很大帮助。

ntb = NoninteractiveTextBox
ntb(root, location, 80, 10)

我们可以说,这是一种非常不寻常的尝试创建 class 实例的方法 :-)

第一行将 ntb 设置为对 class、 的引用,而不是 class.[=21= 的实例]

因为 ntbNoninteractiveTextBox 现在实际上是对 class 的相同引用,第二行是一样的,就好像后者被用来代替前者(这是, 顺便说一句,为什么它没有因为缺少 self):

而失败
NoninteractiveTextBox(root, location, 80, 10)

换句话说,它创建一个实例,但立即将其丢弃,因为您没有将它分配给任何东西。

这行的问题就在于此:

ntb.inject_text("testing text for NTB")

因为 ntb 是 class 而不是一个实例,它被认为是 class 方法调用,它不会自动提供 self 作为第一个范围。这就是它抱怨缺少参数的原因。

您应该改用它,将 ntb 设置为 class 的 实例 ,并允许它这样使用:

ntb = NoninteractiveTextBox(root, location, 80, 10)

应该是:

ntb = NoninteractiveTextBox(root, location, 80, 10)
ntb.inject_text("testing text for NTB")