【问题标题】:I'm trying to develop tkinter app using oops but getting this error我正在尝试使用 oops 开发 tkinter 应用程序但收到此错误
【发布时间】:2021-05-24 09:30:15
【问题描述】:

我刚刚开始练习 Oops 概念。我正在观看简单的 Oops 视频并尝试将应用步骤应用于 tkinter 问题。我不知道为什么会收到此错误。

from tkinter import *
from tkinter import font as tkFont

top = Tk()
top.minsize(width=1280,height=720)
top.maxsize(width=721,height=521)
class Framesone:
    def __init__(self, x1, y1, frame1, text1, x2, y2):
        self.stframe = LabelFrame(top, width=300, height=200, highlightcolor="grey", bd=5)
        self.stframe.place(x=x1, y=y1)
        self.label1 = Label(frame1, text=text1)
        self.label1.config(font=("Times", "25", "bold", "italic"))
        self.label1.place(x=x2, y=y2)
Framesone(100,200,Framesone().stframe,"HI",20,30)
top.mainloop()

输出

Traceback (most recent call last):
  File "E:/python projects my/Basic Programs/MQC FIt Software.py", line 14, in <module>
    Framesone(100,200,Framesone().stframe,"HI",20,30)
TypeError: __init__() missing 6 required positional arguments: 'x1', 'y1', 'frame1', 'text1', 'x2', and 'y2'

Process finished with exit code 1

【问题讨论】:

  • 当您使用:Framesone().stframe 时,您首先调用 Framesone(),不带任何参数,但它需要 6 个参数。
  • 另外我想知道为什么您要生成 Framesone 对象而不保留它。似乎您正在使用对象初始化,就好像它是一个函数一样。

标签: python oop tkinter


【解决方案1】:
Framesone(100,200,Framesone().stframe,"HI",20,30)

Framesone().stframe 调用不带参数的__init__ 函数。 每次调用 MyClass() 时,都会调用该类的 __init__ 函数。

【讨论】:

    【解决方案2】:

    当您调用Framesone().stframe 时,代码首先调用Framesone()__init__() 函数,但没有任何参数。在声明对象本身之前,您正在使用对象的实例变量。

    由于您已经在对象中定义了 stframe,您可以简单地将对 frame1 的引用替换为 self.stframe,就像在您的示例中一样。

    class Framesone:
        def __init__(self, x1, y1, text1, x2, y2):
            self.stframe = LabelFrame(top, width=300, height=200, highlightcolor="grey", bd=5)
            self.stframe.place(x=x1, y=y1)
            self.label1 = Label(self.stframe, text=text1)
            self.label1.config(font=("Times", "25", "bold", "italic"))
            self.label1.place(x=x2, y=y2)
    
    Framesone(100, 200, "HI", 20, 30)
    

    如果您确实想以现在使用的方式使用此 stframe,可以将 stframe 声明移到 __init__() 函数之外。这会将stframe 从实例变量更改为静态变量。这将允许您从类外部调用 Framesone.stframe 而无需调用其构造函数。 (请注意,您现在调用 Framesone 而没有 () 表明您正在使用其静态类变量而不是实例变量。)

    class Framesone:
        stframe = LabelFrame(top, width=300, height=200, highlightcolor="grey", bd=5)
        
        def __init__(self, x1, y1, frame1, text1, x2, y2):
            self.stframe.place(x=x1, y=y1)
            self.label1 = Label(self.frame1, text=text1)
            self.label1.config(font=("Times", "25", "bold", "italic"))
            self.label1.place(x=x2, y=y2)
    
    Framesone(100, 200, Framesone.stframe, "HI", 20, 30)
    

    编辑:从类静态变量中删除 self。为了更好地解释实例与静态变量,稍微更改了措辞

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-22
      • 2021-02-16
      • 2019-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多