简体   繁体   中英

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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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