简体   繁体   English

Tkinter 按钮绑定抛出额外参数错误

[英]Tkinter button bind throws extra argument error

I am trying to write tkinter code that calls a function either when a button is clicked or when enter is clicked when the button is in focus.我正在尝试编写tkinter代码,该代码在单击按钮时或在按钮处于焦点时单击 enter 时调用 function。 I have the following code:我有以下代码:

import tkinter as tk

m = tk.Tk(className="My window")
def callback():
    print("Ice cream weather")

butt = tk.Button(m, text="My button", width=25, command=callback)
butt.grid()
butt.focus_set()
butt.bind('<Return>', callback)
m.mainloop()

But when I run it and press Enter , I get the following error:但是当我运行它并按Enter时,出现以下错误:

Traceback (most recent call last):
  File "C:\Users\chiller\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
TypeError: callback() takes 0 positional arguments but 1 was given

I found a solution, which I posted below, but I am wondering if there is a simpler or neater fix.我找到了一个解决方案,已在下面发布,但我想知道是否有更简单或更整洁的修复方法。

A way to solve this is to set the function up to take in a dummy parameter, and set a default value for when it isn't passed (ie for button click, which passes 0 arguments).解决这个问题的一种方法是将 function 设置为接受一个虚拟参数,并在未传递时设置默认值(即按钮单击,传递 0 个参数)。 This is just changing the line这只是改变线路

def callback():

To

def callback(pointless=None):

This gives the extra parameter from pressing Enter a place to go, while not requiring it for a button push.这提供了从按下Enter到 go 的额外参数,而不需要它来按下按钮。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM