Skip to main content
 首页 » 编程设计

python之TypeError : takes 0 positional arguments but 3 were given. 无法弄清楚是什么参数

2024年11月01日11bjzhanghao

我正在编写一个 tkinter 用户界面。 我希望能够在每次更改时访问条目(用户添加一个字符) 所以我想我应该像这样使用回调函数

def callback(): 
     s = entry.get() 
     print (s) 
     varStr.trace_variable("w", callback) 

然后我调用该函数。但我不确定它们是如何工作的,也找不到答案。

当我运行程序时,一旦我在 Entry 字段中输入一个字符,我就得到了这个错误:

Exception in Tkinter callback 
Traceback (most recent call last):   
  File "C:\Program Files\Python33\lib\tkinter\__init__.py", line 1475, in __call__ 
    return self.func(*args) 
TypeError: callback() takes 0 positional arguments but 3 were given 

我找到了可以添加“self”的地方,但我还有两个参数需要填写。你能帮我知道它们应该是什么吗?

请您参考如下方法:

如果没有您为 callback() 使用的确切小部件,很难准确地说出 TKInter 试图传递给它的参数。

你总是可以给回调一个可变参数参数:

def callback(*args): 
    s = entry.get() 
    print (s) 
    varStr.trace_variable("w", callback) 

来自 this document您可以看到 trace_variable() 回调传递了三个参数:

  • The name of the Tk variable. This is not the Tk variable object itself, but you can use the name to get or set the value via root.globalgetvar(name) and root.globalsetvar(name). Unfortunately, I have not found any way to obtain the actual Tk variable object from its name; root.nametowidget(varName) does not seem to work for Tk variables.
  • The variable index, if the Tk variable is an array, else an empty string. I have no idea how to create a Tk variable array in Tkinter (but it is easy in Tk). If you figure it out, you can then determine if the index is a string representation of an integer, or an integer (my guess is it's a string).
  • The access mode, one of "w", "r" or "u".

但是,您不需要每次调用 callback() 时都需要调用 varStr.trace_variable()。