翻译文本变量,然后将其放在 tkinter 标签中



我正在使用python开发一个非常基本的翻译应用程序。本质上,它将您输入的任何内容放入输入框中,替换一些字母(例如,将"a"变成"u"(,然后将其显示为标签。不幸的是,您输入的单词永远不会被翻译,它只是保持原样。控制台中不显示任何错误。以下是应该执行此操作的代码位:

eword = StringVar()
Entry1 = Entry(root, textvariable=eword, width=30, bg="lightgrey").place(x=250, y=155)
def translate(eword):
translation = ""
for letter in eword:
if letter in "a":
translation = translation + "e"
elif letter in "m":
translation = translation + "n"
else:
translation = translation + letter
return translation

def doit():
text = eword.get()
label3 = Label(root, text=text, font=("Arial", 20), bg="white").place(x=195, y=300)
return

我是python的绝对初学者,所以请简单地解释一下。

我已经对布局进行了一些修改,并添加了必要的代码来运行它。

StringVar 不是一个普通的字符串。要读取其值,您需要使用方法get(),要写入它,请使用set()

当你创建条目时:Entry1 = Entry(root, ...).place(x=250, y=155)变量Entry1将得到值None,因为这就是place()返回的值。我已经将条目的创建与放置在窗口上分开。另外,我正在使用pack()而不是place().

我添加了一个按钮来启动翻译,因为我在您的代码中找不到任何机制。按下按钮时translate()调用函数。

from tkinter import *
root = Tk()                 # Application main window
root.geometry('300x200')    # Setting a size
eword = StringVar()
entry1 = Entry(root, textvariable=eword, width=30)
entry1.pack(pady=20)    # Pack entry after creation 
def translate():
original = eword.get()  # Read contents of eword
translation = ""
for letter in original:
if letter in "a":
translation = translation + "e"
elif letter in "m":
translation = translation + "n"
else:
translation = translation + letter
new_text.set(translation)  # Write translation to label info
action = Button(root, text='Translate', command=translate)
action.pack()   # Pack button after creation 
new_text = StringVar()
info = Label(root, textvariable=new_text)
info.pack(pady=20)
root.mainloop()

与其循环遍历字符串,不如使用replace()

original.replace('a', 'e')
original.replace('m', 'n')

您可能还想研究字符串函数translate():)

最新更新