Call the same function when clicking the Button and pressing enter

扶醉桌前 提交于 2019-12-01 08:27:32
Kevin

You can create a function that takes any number of arguments like this:

def clickOrEnterSubmit(self, *args):
    #code goes here

This is called an arbitrary argument list. The caller is free to pass in as many arguments as they wish, and they will all be packed into the args tuple. The Enter binding may pass in its 1 event object, and the click command may pass in no arguments.

Here is a minimal Tkinter example:

from tkinter import *

def on_click(*args):
    print("frob called with {} arguments".format(len(args)))

root = Tk()
root.bind("<Return>", on_click)
b = Button(root, text="Click Me", command=on_click)
b.pack()
root.mainloop()

Result, after pressing Enter and clicking the button:

frob called with 1 arguments
frob called with 0 arguments

If you're unwilling to change the signature of the callback function, you can wrap the function you want to bind in a lambda expression, and discard the unused variable:

from tkinter import *

def on_click():
    print("on_click was called!")

root = Tk()

# The callback will pass in the Event variable, 
# but we won't send it to `on_click`
root.bind("<Return>", lambda event: on_click())
b = Button(root, text="Click Me", command=frob)
b.pack()

root.mainloop()

You could also assign a default value (for example None) for the parameter event. For example:

import tkinter as tk

def on_click(event=None):
    if event is None:
        print("You clicked the button")
    else:
        print("You pressed enter")


root = tk.Tk()
root.bind("<Return>", on_click)
b = tk.Button(root, text='Click Me!', command=on_click)
b.pack()
root.mainloop()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!