Reputation: 1
I am trying to make some tweaks to code that I found on GitHub. The tkinter gui works perfectly but I want to bind the enter button to the 'Get Response' button:
class TkinterGUIExample(tk.Tk):
def initialize(self):
'''
Set window layout.
'''
self.grid()
self.usr_input = ttk.Entry(self, state='normal')
self.usr_input.grid(column=0, row=0, sticky='nesw', padx=3, pady=3)
self.respond = ttk.Button(self, text='Get Response', command=self.get_response)
self.respond.grid(column=1, row=0, sticky='nesw', padx=3, pady=3)
self.conversation_lbl = ttk.Label(self, anchor=tk.E, text='Conversation:')
self.conversation_lbl.grid(column=0, row=1, sticky='nesw', padx=3, pady=3)
self.conversation = ScrolledText.ScrolledText(self, state='disabled')
self.conversation.grid(column=0, row=2, columnspan=2, sticky='nesw', padx=3, pady=3)
So I know where my button is, but I don't know how, when, or where to bind it, while using the same syntax.
My full code can be found here: https://github.com/graylu21/ELIZA-ChatterBot/blob/master/ELIZAChatterBot.py
Upvotes: 0
Views: 192
Reputation: 1
Got it to work! Found the solution in a comment at: How to bind the Enter key to a button in Tkinter
Instead of binding the Enter key to the button, I bound it to the Entry window!
self.usr_input = ttk.Entry(self, state='normal')
self.usr_input.grid(column=0, row=0, sticky='nesw', padx=3, pady=3)
self.usr_input.focus() #Sets focus to the input bar at start
self.usr_input.bind('<Return>', lambda e: self.get_response()) #Binds the Enter key
self.respond = ttk.Button(self, text='Get Response', command=self.get_response)
self.respond.grid(column=1, row=0, sticky='nesw', padx=3, pady=3)
Upvotes: 0
Reputation: 49330
Simply add a binding to '<Return>'
:
self.respond = ttk.Button(self, text='Get Response', command=self.get_response)
self.respond.grid(column=1, row=0, sticky='nesw', padx=3, pady=3)
self.bind('<Return>', self.get_response)
Whenever you press Enter/Return (Tkinter uses the latter because '<Enter>'
refers to when the mouse cursor enters a widget) while the self
window is active, it will call self.get_response
.
Upvotes: 1