You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在输入时实时获取Tkinter Text Box中的输入内容?

实时获取Tkinter文本编辑器输入内容的解决方案

Hey there! I get that you want to automatically capture the text as users type (or modify) content in your Tkinter Text editor, instead of only grabbing it when you call functions like saveFile(). Let's fix that right up.

核心思路:利用Tkinter的虚拟事件

The ScrolledText widget (which inherits from the base Text widget) has a handy virtual event called <<Modified>> — this triggers every time the text content changes, whether it's from typing, pasting, deleting, or any other edit action. We can bind this event to a custom function that will grab the current text instantly.

修改后的完整代码

Here's your updated code with the real-time text capture added:

from tkinter import Tk, scrolledtext, Menu, filedialog, END, messagebox, simpledialog, StringVar

root = Tk(className=" Text Editor")
textArea = scrolledtext.ScrolledText(root, width=100, height=80)

def on_text_change(event):
    # Reset the modified flag so the event will trigger again next time
    textArea.edit_modified(False)
    # Get the current text (exclude the trailing newline)
    current_text = textArea.get('1.0', END+'-1c')
    # Do whatever you want with the current text here!
    # For example, print it to the console (truncated for readability):
    print("Current text:", current_text[:50], "..." if len(current_text) >50 else "")

def newFile():
    if len(textArea.get('1.0', END+'-1c')) > 0:
        if messagebox.askyesno("Save ?", "Do you wish to save ?"):
            saveFile()
        else:
            textArea.delete('1.0', END)
    root.title("TEXT EDITOR")

def openFile():
    textArea.delete('1.0', END)
    file = filedialog.askopenfile(parent=root, mode='rb', title='Select a text file', filetypes=(("Text file", "*.txt"), ("All files", "*.*")))
    if file != None:
        contents = file.read()
        textArea.insert('1.0', contents)
        file.close()

def saveFile():
    file = filedialog.asksaveasfile(mode='w')
    if file != None:
        data = textArea.get('1.0', END+'-1c')
        file.write(data)
        file.close()

menu = Menu(root)
root.config(menu=menu)

fileMenu = Menu(menu)
menu.add_cascade(label="File", menu=fileMenu)
fileMenu.add_command(label="New", command=newFile)
fileMenu.add_command(label="Open", command=openFile)
fileMenu.add_command(label="Save", command=saveFile)
fileMenu.add_command(label="Find")
fileMenu.add_separator()
fileMenu.add_command(label="Exit")

helpMenu = Menu(menu)
menu.add_cascade(label="Help")
menu.add_cascade(label="About")

# Bind the text change event to our function
textArea.bind('<<Modified>>', on_text_change)

textArea.pack()
root.mainloop()

关键修改说明

  • We added the on_text_change function: this is where you'll handle the real-time text. The first thing it does is reset the edit_modified flag to False — if you don't do this, the <<Modified>> event will only trigger once, not every time the text changes.
  • We bind the event to the text area with textArea.bind('<<Modified>>', on_text_change) — this connects the text modification event to our custom function.
  • Inside on_text_change, we grab the current text just like you do in saveFile(), and you can replace the print statement with any logic you need (like updating a preview, saving to a temp file, etc.).

备选方案:键盘事件绑定

If you only want to trigger when a key is released (instead of all text modifications), you can use the <KeyRelease> event instead:

textArea.bind('<KeyRelease>', on_text_change)

Just note that this won't catch changes from pasting via right-click or menu options, so the <<Modified>> event is usually the better choice for full coverage.

内容的提问来源于stack exchange,提问作者Nishan Madhuwantha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:45:12