【问题标题】:tkinter TypeError: missing 1 required positional argument:tkinter TypeError:缺少 1 个必需的位置参数:
【发布时间】:2017-02-28 12:41:10
【问题描述】:

我是python新手,正在练习,我现在已经写了这段代码,但是我遇到了一个错误,我不知道如何解决,有人可以帮我吗?

这是我的代码:

from tkinter import *

root = Tk()

name = 'donut'

def printInput(event, name):
    print("Your name is %s, and you are years old." % (name))

button_1 = Button(root, text="Submit")
button_1.bind("<Button-1>", printInput)
button_1.pack()

root.mainloop()

当我点击提交时,我得到了这个错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\error\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
TypeError: printInput() missing 1 required positional argument: 'name'

我做错了什么?

谢谢!

【问题讨论】:

  • print("Your name is %s, and you are %s years old." % name) 中有两个%s 占位符,但您只提供一个数据。你需要print("Your name is %s, and you are %s years old." % name, something_else_here)
  • @roganjosh 哦,谢谢,我现在修好了,但我得到了同样的错误......虽然只有当我点击提交时才会出现错误
  • 说“我现在修复了它,但得到了同样的错误”显然意味着你没有正确修复它。您应该更具体并编辑您的问题以反映您所谓的“修复”和确切错误消息。
  • 我要用 tkinter 标签来标记它。我可以让它工作,但它只在我最后关闭窗口时打印消息。自从我用 tkinter 做任何事情以来已经有一段时间了,所以我不记得正确的方法了。
  • @l'L'l 使用新代码编辑问题

标签: python tkinter


【解决方案1】:

你有函数printInput,它有两个参数,但是当它被调用时,tkinter 只传递一个参数,即事件。

传递名称参数的一种方法是使用 lambda 函数:

button_1.bind("<Button-1>", lambda event:printInput(event,name))

这会将全局 name 变量作为参数传递给函数。

【讨论】:

    【解决方案2】:

    tkinter 将只使用一个参数调用您的函数。您的函数需要 2 所以它会中断。只需从函数中引用全局值name

    def printInput(event):
        print("Your name is %s, and you are years old." % (name))
    

    对于小型学习程序,这可能没问题,但您可能希望找到一种更好的方法将该值添加到您的函数中,而不是在创建更大、更复杂和/或可重用的脚本时使用全局。

    一种方法是在使用库函数functools.partial 将其传递给tkinter 小部件之前部分应用您的函数。

    from functools import partial
    # ...
    
    button_1.bind("<Button-1>", partial(printInput, name=name))
    

    您可以创建一个预先加载 name 关键字参数的新函数并将其传递给按钮,该函数只需要一个参数并且一切正常。

    【讨论】:

    • 我有点迂腐,也许离题了,但这不是很刻板,这是部分应用。如果它是咖喱,它看起来更像:from somewhere import curry;def printInput(name, event): ...;printInput=curry(printInput);button_1.bind("&lt;Button-1&gt;", printInput(name))
    • 是的,我确定。仔细想想,这两者并不完全相同。我会改变答案。谢谢你把我拉上来。
    猜你喜欢
    • 1970-01-01
    • 2013-07-06
    • 2019-06-25
    • 2013-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多