【问题标题】:Inserting dynamic user input into text() box将动态用户输入插入 text() 框中
【发布时间】:2017-12-01 04:12:17
【问题描述】:

我试图弄清楚我如何可能从一个 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()

【问题讨论】:

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


    【解决方案1】:

    我对此的解决方案是将文本小部件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()
    

    【讨论】:

    • 完美!非常感谢。
    猜你喜欢
    • 2011-10-07
    • 1970-01-01
    • 2021-11-18
    • 2013-10-28
    • 2015-06-21
    • 1970-01-01
    • 2015-06-13
    • 2017-10-23
    • 2016-01-25
    相关资源
    最近更新 更多