【问题标题】:tkinter python function takes 1 argument, given 2tkinter python 函数接受 1 个参数,给定 2
【发布时间】:2016-08-12 00:17:34
【问题描述】:

当我尝试运行我的代码时遇到此错误:

File "./countdown.py", line 36, in <module>
    app = Application(root)
File "./countdown.py", line 16, in __init__
    self.create_buttons(self)
TypeError: create_buttons() takes exactly 1 argument (2 given)

这是我的代码:

import Tkinter as tk

class Application(tk.Frame):
  """Countdown app - simple timer"""

  def __init__(self, master):
    """initialize frame"""
    tk.Frame.__init__(self, master)
    #super(Application, self).__init__(master)
    self.grid()
    self.create_buttons(self)

  def create_buttons(self):
    self.startBttn = Button(app, text = "Start")
    self.startBttn.grid()
    self.stopBttn = Button(app, text = "Stop")
    self.stopBttn.grid()
    self.resetBttn = Button(app, text = "Reset")
    self.resetBttn.grid()


### Main Code ###

# create the root window using Tk - an object of tkinter class
root = tk.Tk()

# modify the prog. window (set size, title, etc.)
root.title("Countdown")
root.geometry("200x100")
#instantiate Application
app = Application(root)

我一直在寻找这个问题的答案,但无法将其他人的解决方案应用于我的代码 - 有什么想法吗?如果我删除 tk.在类 Application 声明中的 Frame 之前,我收到一个错误,提示找不到 Frame。如果我使用 super(Application, self).__init__(master) 而不是它上面的行,我会得到一个类型错误必须是类而不是类对象。

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    调用绑定方法时不要显式传递self。像这样称呼它:

    self.create_buttons()
    

    通过使用self.create_buttons(self) 调用方法,函数接收两个 参数:调用绑定方法时传递的隐式self(Python 自动执行此操作)和显式self你在方法调用中传递。


    create_buttons() 还存在一些其他问题,您可以使用以下代码解决这些问题:

      def create_buttons(self):
        self.startBttn = tk.Button(self, text = "Start")
        self.startBttn.grid()
        self.stopBttn = tk.Button(self, text = "Stop")
        self.stopBttn.grid()
        self.resetBttn = tk.Button(self, text = "Reset")
        self.resetBttn.grid()
    

    更改是您需要使用tk.Button 来引用Button 类,并将self 传递给tk.Button,这是对父框架的引用。这里selfApplication 实例,它是tk.Frame 的子类——因此self 是一个框架。

    最后你需要添加对mainloop()的调用:

    #instantiate Application
    app = Application(root)
    root.mainloop()
    

    关于super 的问题,tkinter 类属于“旧式”类型,不支持super()。因此,您必须使用tk.Frame.__init__(self, master) 调用基类。

    有一种解决方法是使用多重继承并将object 作为基类。如果您将Application 声明为:

    class Application(tk.Frame, object):
        def __init__(self, master):
            """initialize frame"""
            super(Application, self).__init__(master)
    

    那么你可以使用super(),但这并不值得。

    【讨论】:

    • app.mainloop() 用于要绘制的窗口和要处理的事件。
    • @AbhishekBalajiR:啊,是的,这也是必需的,谢谢。
    • @potatopie:太好了!如果您愿意,可以接受答案。
    猜你喜欢
    • 2022-01-05
    • 2020-12-16
    • 2021-05-01
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多