tkinter 类型错误:缺少 1 个必需的位置参数: [英] tkinter TypeError: missing 1 required positional argument:

查看:60
本文介绍了tkinter 类型错误:缺少 1 个必需的位置参数:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I´m new to python and practicing, and I have now written this piece of coding, but I´m getting an error I do not know how to resolve, could someone help me please?

这是我的代码:

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

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

And when I click on submit, I get this error:

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'

我做错了什么?

谢谢!

推荐答案

tkinter 将仅使用一个参数调用您的函数.您的函数需要 2,因此它会中断.只需从函数中引用全局值 name

tkinter will call your function with only one argument. Your function expects 2 so it breaks. Just refer to the global value name from the function

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

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

For a small learner program this might be ok but you may wish to find a nicer way to get that value into your function than using a global as you create larger more complex and/or reusable scripts.

一种方法是在使用库函数 functools.partial.

One way to do that is to partially apply your function before passing it to the tkinter widget using the library function functools.partial.

from functools import partial
# ...

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

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

You can create a new function with the name keyword argument preloaded and pass it to the button, this function only expects one argument and it all works ok.

这篇关于tkinter 类型错误:缺少 1 个必需的位置参数:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆