Calling up the same function by pressing a button and pressing a key

I have a GUI that has an Entry widget and a submit Button .

Basically I am trying to use get() and print the values ​​inside the Entry widget. I wanted to do this by clicking submit Button or pressing enter or returning to the keyboard.

I tried to associate the event "<Return>" with the same function that is called when I press the submit button:

 self.bind("<Return>", self.enterSubmit) 

But I have an error:

2 arguments required

But the self.enterSubmit function accepts only one, since the command parameter for Button requires only one.

To solve this problem, I tried to create 2 functions with the same functionality, they just have a different number of arguments.

Is there a more efficient way to resolve this issue?

+4
source share
2 answers

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

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

This is called a list of arbitrary arguments . The caller can freely pass as many arguments as he wants, and all of them will be packed into the args tuple. The "Enter" binding can be passed to its 1 event object, and the click command can take 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 by pressing Enter and pressing the button:

 frob called with 1 arguments frob called with 0 arguments 

If you don't want to change the signature of the callback function, you can wrap the function you want to bind in the 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() 
+10
source

You can also assign a default value (e.g. None ) to the event parameter. For instance:

 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() 
+3
source

Source: https://habr.com/ru/post/1492311/


All Articles