python - 当输入字段为空并单击翻译按钮时,如何使输出字段在 Tkinter 中不返回任何内容?
问题描述
我正在使用 python 字典推进翻译应用程序项目。有输入字段、翻译按钮和输出字段。当条目与字典中的键不匹配时,会显示一个错误代码(“找不到单词”)。但是现在,当输入字段为空并且您单击按钮时,它仍然返回“找不到单词”,这有点愚蠢。当用户没有输入任何单词时,我如何不返回任何内容?谢谢。下面是代码:
from tkinter import *
import tkinter. messagebox
root=Tk()
root.geometry('250x250')
root.title("Meta' Translator")
root.configure(background="#35424a")
#Entry widget object
textin = StringVar()
#press ENTER key to activate translate button
def returnPressed(event):
clk()
def clk():
entered = ent.get().lower() #Get user input and convert to lowercase
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 insertion point on entry field
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)
#press ENTER key to activate Translate button
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={
"hat":"ɨ̀də̀m",
"hoe":"əsɔ́",
"honey":"jú",
"chest":"ɨgɔ̂",
"eye":"ɨghə́",
"ear":"ǝ̀tǒŋ",
}
root.mainloop()
解决方案
你试过这个:
def clk():
entered = ent.get().lower() #Get user input and convert to lowercase
output.delete("0.0", END)
if len(entered.strip(" ")) > 0:
try:
textin = exlist[entered]
except:
textin = "Word not found"
output.insert("0.0", textin)
基本上,如果字符串的长度为 0,它就不会运行代码。
推荐阅读
- arduino-c++ - 如何解决循环数字
- c# - 在单行 C# 和 ASP.NET MVC 中获取不同行的 db 值
- c# - DistributedCacheExtensions 函数
- r - 看不到使用 Docker 和 {golem} 构建的暴露的 Shiny 应用程序
- groovy - 将 shell 输出传递给 groovy 变量
- android - imageview中的Recryler如何使不可见
- java - 'maven package' 在尝试构建 java 项目时出错
- websocket - Quarkus websockets - 具有 1xx HTTP 响应的内容长度
- angularjs - Angularjs + 使用 XLSX.utils.table_to_book 将嵌套数据导出到 Excel
我正在使用 Angularjs + XLSX ( https://sheetjs.com/ ) 将我的 html 导出到 excel。对于简单的表,它工作正常。但是当我尝试使用
XLSX.utils.table_to_book
- azure-devops - 有没有办法使用 GIT Flow 管理 Azure 数据工厂的开发?