python - 错误说明 - 'statInter' 对象没有属性 'tk'

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

我正在尝试在 Python 中创建一个简单的计时器,并打算使用类构建用户界面。我想使用这些类来初始化用户界面。然后在主体的正文中,我想使用 .grid 和 .configure 方法添加属性。但是当我尝试这样做时,出现错误:'statInter' object has no attribute 'tk'。

我是编程的初学者,但如果我正确理解错误,它的结果是因为 .grid 和其他 Button 方法不是由我的 statInter(即静态接口(interface))类继承的。它是否正确?我该如何解决这个错误?我确实继承了 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()

最佳答案

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

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

您还没有遇到其他问题,但可能很快就会遇到。为避免这种情况,您还需要在显式调用 button()field() 中的基类方法时显式传递 self .

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()

关于python - 错误说明 - 'statInter' 对象没有属性 'tk',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37899043/

相关文章:

python - 使用 numpy 数组将值分配给另一个数组

python - 有没有办法检查针对 django 版本的功能弃用?

php - mysql在php函数中选择*或所需参数

class - 以下方法如何使用保留给构造函数的 “syntactic sugar”?

python - 如何使用 Twisted 运行 Klein?

python - 类型错误 : expected string or buffer

python - Tensorflow 的多边形边界框

excel - VBA 对象数据在集合中被覆盖

python-3.x - requests.exceptions.MissingSchema : Invalid URL 'None' : No schema supplied while trying to find broken links through Selenium and Python

python-3.x - 如何让 Python "import.util.module_from_spec"更像 "import"”?