2

I have a skeleton of a program that I want to use:

from tkinter import *
import urllib
import urllib.request
import xml.etree.ElementTree as ET
root = Tk()

def program():
    print('Hello')

tex=Text(root)
tex.pack(side='right')
inputfield = Entry(root)
inputfield.pack(side='bottom')
text = inputfield.get()
but = Button(root,text="Enter", command = program) 
but.pack(side='bottom')

root.mainloop()

Alright so recapping, the program is just a frame with a text field, input field and a button that says Enter. I want to call the program the button calls without actually pressing the button. I want to input the text in the input field and press Enter on my keyboard to call the function.

Is that possible through tkinter?

udondan
  • 57,263
  • 20
  • 190
  • 175
user1985351
  • 4,589
  • 6
  • 22
  • 25

1 Answers1

6

Yes, it is possible. You only have to bind the Entry widget with the event <Return>:

inputfield.bind('<Return>', lambda _: program())

Since the callback function used in bind receives one argument (a Tkinter event), you cannot use the reference to program directly. So instead of changing the definition of the function, you can use a lambda and name the first argument as _, a common name for "don't care" variables.

Community
  • 1
  • 1
A. Rodas
  • 20,171
  • 8
  • 62
  • 72
  • If you're going to use some "magic" syntax (the underscore as an argument to lambda), your answer would be much more useful if you explained why that was (or wasn't) necessary. You don't want a beginner to just blindly start using this convention without knowing what it does. – Bryan Oakley Jun 09 '13 at 18:33
  • @BryanOakley so what is the difference between the underscore and using "lambda: funcName()" ? – Jona Jan 24 '16 at 18:06
  • @Jona: the lambda requires an argument, so `lambda: funcName()` would throw an error. My point was, using the unconventional argument name `_` is less clear than the more common name `event`. – Bryan Oakley Jan 24 '16 at 20:42
  • ah ha, brilliantly simply explained. thanks @BryanOakley – Jona Jan 24 '16 at 20:54