翻译textvariable,然后将其放入tkinter实验室

2024-06-02 04:21:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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的初学者,所以请简单地解释一下。在


Tags: textin应用程序内容returndef字母place
1条回答
网友
1楼 · 发布于 2024-06-02 04:21:46

我已经拼凑了一点布局,并添加了运行它所需的代码。在

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

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

我添加了一个按钮来启动翻译,因为我在你的代码中找不到任何机制。按下按钮时,该按钮调用函数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()代替在字符串中循环:

^{pr2}$

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

相关问题 更多 >