将动态用户输入插入text()框

2024-10-02 22:33:30 发布

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

我正在尝试如何从一个text()框中获取用户输入,并将其插入到已插入文本之间的另一个text()框中,并使其实时自动更新。在

简化示例代码:

from Tkinter import *

root = Tk()

hello = Label(text="hello, what's your name?")
hello.grid(sticky=W)

mynameisLabel = Label(text="My name is:")
mynameisLabel.grid(row=1, sticky=W)

responseEntry = Text(width=40, height=1)
responseEntry.grid(row=1, sticky=E)

conclusionText = Text(width=40, height=5)
conclusionText.insert(END, "Ah, so your name is ")

# here is where I intend to somehow .insert() the input from responseEntry

conclusionText.insert(END, "?")
conclusionText.grid(row=2, columnspan=2)

root.mainloop()

Tags: textnamefromhelloyourisrootlabel
1条回答
网友
1楼 · 发布于 2024-10-02 22:33:30

我必须解决这个问题的方法是将文本小部件responseEntry绑定到正在释放的键上,然后使用一个小函数,以便每次发生这种情况时,都会重新写入文本。这看起来是这样的:

from Tkinter import *

root = Tk()

hello = Label(text="hello, what's your name?")
hello.grid(sticky=W)

mynameisLabel = Label(text="My name is:")
mynameisLabel.grid(row=1, sticky=W)

responseEntry = Text(width=40, height=1)
responseEntry.grid(row=2, sticky=E)

conclusionText = Text(width=40, height=5)
conclusionText.insert(END, "Ah, so your name is ?")
conclusionText.grid(row=3, columnspan=2)

# This function is called whenever a key is released
def typing(event):
    name = responseEntry.get("1.0",END) # Get string of our name
    conclusionText.delete("1.0", END)   # delete the text in our conclusion text widget
    conclusionText.insert(END, "Ah, so your name is " + name[:-1] + "?") # Update text in conclusion text widget. NOTE: name ends with a new line

responseEntry.bind('<KeyRelease>', typing) # bind responseEntry to keyboard keys being released, and have it execute the function typing when this occurs

root.mainloop()

相关问题 更多 >