【问题标题】:__init__() missing 2 required positional arguments__init__() 缺少 2 个必需的位置参数
【发布时间】:2019-02-08 05:51:31
【问题描述】:

请帮帮我。在这个创建按钮的简单 tkinter 程序中,我提供了所有三个参数,但有关位置参数的错误出现在屏幕上。对不起我的英语不好。

from tkinter import *

class Button:
def __init__(self, row, column, frame):
    self.row = row
    self.column = column
    b = Button(frame).grid(row = self.row, column = self.column)

tk = Tk()
b1 = Button(row = 1, column = 1, frame = tk)
tk.mainloop()

还有错误:

重新启动:C:\Users\vnira\Documents\python.projects\Flappy Bird\whiteboard.py
回溯(最近一次通话最后一次):
文件“C:\Users\vnira\Documents\python.projects\Flappy Bird\whiteboard.py”,第 11 行,在
b1 = 按钮(行 = 1,列 = 1,框架 = tk)
init
中的文件“C:\Users\vnira\Documents\python.projects\Flappy Bird\whiteboard.py”,第 7 行 Button(frame).grid(row = self.row, column = self.column)
TypeError:init() 缺少 2 个必需的位置参数:'column' 和 'frame'

提前致谢

【问题讨论】:

    标签: python python-3.x tkinter


    【解决方案1】:
    from tkinter import *
    
    class Buttons:
        def __init__(self, row, column, frame):
            self.row = row
            self.column = column
            b = Button(frame).grid(row = self.row, column = self.column)
    
    tk = Tk()
    b1 = Buttons(row = 1, column = 1, frame = tk)
    tk.mainloop()
    

    当 tkinter 有一个类 Button 时,你创建了一个类 Button。使用您自己的变量名可能会有所帮助:) 我想它试图递归地创建您创建的 Button 类的实例,而不是创建 tkinter 模块内的 Button 类的实例。

    【讨论】:

      【解决方案2】:

      在Button 类的__init__ 中,您正在尝试处理Button 类的新实例:

      b = Button(frame)
      

      由于button.__init__ 采用3 个参数,row, column, frame 脚本失败。如果你也通过了row 和column,你会遇到递归问题,你会无限地创建Button 的新实例。

      编辑:正如 cmets 和其他答案中所指出的,tkinter 有自己的 Button 类,你正在覆盖它,这就是为什么你应该尽量避免这样做

      from tkinter import *
      

      而只是import tkinter 并致电tkinter.Button。

      【讨论】:

      • 还需要指出的是,通过创建一个名为 Button 的类,他们正在破坏同名的 tkinter 类。
      猜你喜欢
      • 2020-06-13
      • 2021-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-25
      • 2021-02-08
      相关资源
      最近更新 更多