如何在 Tkinter 中使用 Enter 键激活按钮单击?

时间:2021-03-01 11:46:41

标签: python tkinter

我正在开发翻译应用程序。 “翻译”按钮工作正常,但我也希望能够按下 ENTER 键来激活翻译按钮。请问,我该怎么做? (感谢您在我之前的问题中提供的帮助)波纹管是代码:

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()

1 个答案:

答案 0 :(得分:0)

将返回键绑定到一个函数,然后从该函数调用 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()
相关问题