首页 > 解决方案 > How do I activate button click with the Enter key in Tkinter?

问题描述

I'm progressing in the creation of a translation app. The "Translate" button works fine, but I want to be able to press the ENTER key to activate the translate button as well. Please, how do I do this? (Thanks for the help you provided on my previous question) Bellow is the code:

from tkinter import *
import tkinter. messagebox
root=Tk()
root.geometry('250x250')
root.title("Meta' Translator")
root.configure(background="#35424a")

#Entry widget object
textin = StringVar()

def clk():
    entered = ent.get()
    output.delete(0.0,END)
    try:
    textin = exlist[entered]
    except:
        textin = 'Word not found'
    output.insert(0.0,textin)

#heading
lab0=Label(root,text='Translate English Words to Meta\'',bg="#35424a",fg="silver",font=('none 11 
bold'))
lab0.place(x=0,y=2)

#Entry field
ent=Entry(root,width=15,font=('Times 18'),textvar=textin,bg='white')
ent.place(x=30,y=30)

#focus on entry widget
ent.focus()

#Search button
but=Button(root,padx=1,pady=1,text='Translate',command=clk,bg='powder blue',font=('none 18 
bold'))
but.place(x=60,y=90)

#output field
output=Text(root,width=15,height=1,font=('Times 18'),fg="black")
output.place(x=30,y=170)

#prevent sizing of window
root.resizable(False,False) 

#Dictionary
exlist={
    "abdomen":"fɨbûm", "abdomens":"tɨbûm",
    "adam's apple":"ɨ̀fɨ̀g ədɔ'",
    "ankle":"ɨgúm ǝwù", "ankles":"tɨgúm rəwù",
    "arm":"ǝbɔ́", "arms":"ɨbɔ́",
    "armpit":"ǝtón rɨ̀ghá"
    }

root.mainloop()

标签: pythontkinter

解决方案


将返回键绑定到一个函数,然后从该函数调用 clk 函数。

from tkinter import *
import tkinter. messagebox

root=Tk()
root.geometry('250x250')
root.title("Meta' Translator")
root.configure(background="#35424a")

#Entry widget object
textin = StringVar()

def returnPressed(event):
  clk()
  
def clk():
    entered = ent.get()
    output.delete(0.0,END)
    try:
      textin = exlist[entered]
    except:
      textin = 'Word not found'
    output.insert(0.0,textin)

#heading
lab0=Label(root,text='Translate English Words to Meta\'',bg="#35424a",fg="silver",font=('none 11 bold'))
lab0.place(x=0,y=2)

#Entry field
ent=Entry(root,width=15,font=('Times 18'),textvar=textin,bg='white')
ent.place(x=30,y=30)

#focus on entry widget
ent.focus()

#Search button
but=Button(root,padx=1,pady=1,text='Translate',command=clk,bg='powder blue',font=('none 18 bold'))
but.place(x=60,y=90)

root.bind('<Return>', returnPressed)

#output field
output=Text(root,width=15,height=1,font=('Times 18'),fg="black")
output.place(x=30,y=170)

#prevent sizing of window
root.resizable(False,False) 

#Dictionary
exlist={
    "abdomen":"fɨbûm", "abdomens":"tɨbûm",
    "adam's apple":"ɨ̀fɨ̀g ədɔ'",
    "ankle":"ɨgúm ǝwù", "ankles":"tɨgúm rəwù",
    "arm":"ǝbɔ́", "arms":"ɨbɔ́",
    "armpit":"ǝtón rɨ̀ghá"
    }

root.mainloop()

推荐阅读