[英]How do I activate button click with the Enter key in 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()
將返回鍵綁定到 function 並從該 function 調用 clk function。
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.