Tkinter出现“发生异常:AttributeError类型对象'Tk'没有属性'tk'”

时间:2020-10-14 16:30:11

标签: python python-3.x tkinter

我整天都在寻找这个问题的答案,但我很沮丧。我正在制作一个具有7个按钮和2个输入字段的程序。我定义了__init__,并且对上面定义的代码有依赖性。没问题,但是输入和结束脚本有问题。

class root(tk.Tk):
def __init__(self):
    super().__init__()
    frame = tk.Frame()
    button = tk.Button(frame,
                text = "Make New File",
                command=self.answer1)
    button.pack(side=tk.LEFT)

    button2 = tk.Button(frame, 
                text = "Edit File", 
                command = self.answer2)
    button2.pack(side=tk.LEFT)
    button3 = tk.Button(frame, 
                text = "Append Data", 
                command = self.answer3)
    button3.pack(side=tk.LEFT)
    button4 = tk.Button(frame, 
                text = "Read File", 
                command = self.answer4)
    button4.pack(side=tk.LEFT)
    button5 = tk.Button(frame, 
                text = "Delete File", 
                command = self.answer5)
    button5.pack(side=tk.LEFT)
    buttonquit = tk.Button(frame, 
            text="QUIT", 
            fg="red",
            command=quit)
    buttonquit.pack(side=tk.LEFT)
    frame = tk.Frame()
    self.L1 = tk.Label(root, text="File Name")
    self.L1.pack( side = tk.LEFT)
    self.E1 = tk.Entry(root, bd =5)
    self.E1.pack(side = tk.RIGHT)
    L2 = tk.Label(root, text="Text to Edit")
    L2.pack( side = tk.LEFT)
    self.E2 = tk.Entry(root, bd =5)
    self.E2.pack(side = tk.RIGHT)
    title = self.E1.get()
    text = self.E2.get()
    frame = tk.Frame(root)
    frame.pack()
    root.title("Catalog 2020")
john = root()
john.mainloop()

这是错误:

Exception has occurred: AttributeError
type object 'Tk' has no attribute 'tk'
  File "C:\Users\25gbrickner\Desktop\catalogcode\catalog2020-release2.py", line 102, in __init__
    self.L1 = tk.Label(root, text="File Name")
  File "C:\Users\25gbrickner\Desktop\catalogcode\catalog2020-release2.py", line 115, in <module>
    john = root()

我已经搜索了一段时间,但我不明白这个问题。我确实在大代码中定义了命令,但是我将其缩减了。

1 个答案:

答案 0 :(得分:1)

您的代码中有几个问题。首先,您忽略了调用超类的tk.Tk而从__init__继承。

您需要将其添加到__init__的顶部:

super().__init__()

第二,在代码root中是一个类,但是您试图将其用作其他小部件的父级。在这种特定情况下,如果您希望窗口小部件进入根窗口,则需要使用self

self.L1 = tk.Label(self, text="File Name")
self.E1 = tk.Entry(self, bd =5)
L2 = tk.Label(self, text="Text to Edit")
self.E2 = tk.Entry(self, bd =5)
frame = tk.Frame(self)

此外,您还需要命名类Root,因为python中的约定是将类名大写。

类似地,尝试设置标题时遇到问题。您需要致电self.title而不是root.title

self.title("Catalog 2020")

最后,您需要删除james = tk.Tk。它什么也不做,您永远不会使用james。您还需要删除frame = tk.Frame(),因为它会导致您创建两个根窗口。应该永远只有一个。另外,您永远不会使用此frame实例。


与提出的问题无关,您在创建条目窗口小部件后大约一毫秒内致电self.E1.get()self.E2.get(),甚至在用户看到条目窗口小部件之前。

您需要等待调用这些方法,直到用户输入数据并执行了诸如单击按钮或按回车键之类的某种操作之后。