将动态用户输入插入文本()框

时间:2017-06-27 23:41:14

标签: python python-2.7 user-interface tkinter tk

我试图找出如何从一个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()

1 个答案:

答案 0 :(得分:1)

我必须解决的问题是将Text小部件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()