jtor23
jtor23

Reputation: 37

How can I bind the <"Return"> key and button widget to the same function on Tkinter?

I am currently trying to make a GUI that allows a user to either use a button or Enter key to run my program. I was trying to figure out if there was a way where either using the button or pressing Enter could execute the same function without having to rewrite the same function for both actions separately. The <"Return">, Enter, key is currently bound with an entry field I created. Both the key bind and button are set to execute the same function, but no luck. Is this possible? Is there perhaps a better way to achieve this? Below is sample code of what I have so far. Please let me know what would be the best alternative in this scenario, I would very much appreciate it. Thanks.

def but_test(entry):
print(entry)

H = 700
W = 925

root = tk.Tk()

canvas = tk.Canvas(root, bg="#8080ff", height = H, width = W)
canvas.pack(fill = "both", expand = True)

frame = tk.Frame(root, bg='brown', bd=10)
frame.place(relx= 0.08,rely=0.15,relwidth = 0.3, relheight=0.08)

entry = tk.Entry(frame, bg='white',relief = 'sunken')
entry.place(relwidth=0.6, relheight=1)


button = tk.Button(frame, text = "Button", bg='red', command=lambda:but_test(entry.get()))
button.place(relx=0.7,relwidth=0.3, relheight=1)

entry.bind("<Return>", but_test)
     

frame2 = tk.Frame(root, bg='yellow',bd=10)
frame2.place(relx= 0.1, rely = 0.4, relwidth=0.25, relheight=0.5)

label = tk.Label(frame2, bg='white')
label.place(relwidth=1,relheight=1)

root.mainloop()

Upvotes: 1

Views: 1264

Answers (1)

acw1668
acw1668

Reputation: 46669

You can use lambda in bind() as well:

entry.bind("<Return>", lambda e: but_test(entry.get()))

Upvotes: 2

Related Questions