错误解释 - ' statInter'对象没有属性' tk'

时间:2016-06-18 16:11:52

标签: python class python-3.x tkinter tk

我正在尝试在Python中创建一个简单的计时器,并且我的目标是使用类构建用户界面。我想使用这些类初始化用户界面。然后在正文的主要文本中,我想使用.grid和.configure方法添加属性。但是,当我尝试这样做时,错误:' statInter'对象没有属性' tk'出现。

我是编程的初学者,但如果我正确理解了错误,那么因为我的statInter(即静态接口)类不会继承.grid和其他Button方法。它是否正确?我该如何解决这个错误?我试图继承Button类甚至Tk类的属性,但在后一种情况下,我得到一个无限循环,即超出最大递归深度。

感谢您的帮助

#This is a simple timer version

from tkinter import *

window = Tk()
window.title('Tea timer')
window.minsize(300,100)
window.resizable(0,0)

class statInter(Button,Entry):

    def __init__(self, posx, posy):
        self.posx = posx  # So the variables inside the class are defined broadly
        self.posy = posy

    def button(self):
        Button(window).grid(row=self.posx, column=self.posy)

    def field(self):
        Entry(window, width=5)

sth = statInter(1,2)
sth.grid(row=1, column = 2)

window.mainloop()

2 个答案:

答案 0 :(得分:4)

问题是您派生的StatInter类(CamelCasing PEP 8 - Style Guide for Python Code中建议的类名称没有初始化其基类,通常不会&#39 ; t 在Python中隐式发生(就像在C ++中那样)。

为了在StatInter.__init__()方法中执行此操作,您需要知道将包含它的parent小部件(除了顶级窗口之外的所有小部件都包含在一个层次结构) - 所以需要将一个额外的参数传递给派生类的构造函数,以便它可以传递给每个基类构造函数。

您还没有遇到其他问题,但可能很快就会遇到。为了避免这种情况,当您在selfbutton()中显式调用基类方法时,您也将明确地传递field()

from tkinter import *

window = Tk()
window.title('Tea timer')
window.minsize(300,100)
window.resizable(0,0)

class StatInter(Button, Entry):

    def __init__(self, parent, posx, posy):  # Added parent argument
        Button.__init__(self, parent)  # Explicit call to base class
        Entry.__init__(self, parent)  # Explicit call to base class
        self.posx = posx  # So the variables inside the class are defined broadly
        self.posy = posy

    def button(self):
        Button.grid(self, row=self.posx, column=self.posy)  # Add self

    def field(self):
        Entry.config(self, width=5)  # Add self

sth = StatInter(window, 1, 2)  # Add parent argument to call
sth.grid(row=1, column=2)

window.mainloop()

答案 1 :(得分:1)

您收到此错误的原因是您永远不会从您继承的类(ButtonEntry)中调用任何一个构造函数。

如果您将__init__更改为:

def __init__(self, posx, posy):
    Button.__init__(self)
    self.posx = posx  # So the variables inside the class are defined broadly
    self.posy = posy

然后你不会得到你之前遇到的错误,并弹出一个小窗口。在新的__init__中,我们明确调用了Button的构造函数。

与Java和其他一些语言不同,默认情况下不会调用super构造函数。我假设从其他tkinter类继承的每个类必须具有tk字段。通过调用您选择的父构造函数,将创建此字段。但是,如果你没有调用父构造函数,那么这将不是一个已建立的字段,并且你将得到你所描述的错误(' statInter'对象没有属性&# 39; TK&#39)

HTH!