简体   繁体   中英

Event in a text widget when i stop writing with tkinter

I want to execute a function when i stop writing in a text widget. So I use the bind method but I have no found an event to do what I have to do !

I do this :

from tkinter import *
from tkinter import ttk

main = Tk()
main.resizable(width=False, height=False)
main.title("Test")
main.geometry("700x255")

entry = Text(main, wrap=WORD, relief=FLAT, font=helv36, padx=14, pady=15)
entry.place(x='20', y='50')

entry2 = Text(main, width=34, height=9, wrap=WORD, state=DISABLED, relief=FLAT, font=helv36, padx=14, pady=15)
entry2.place(x='380', y='50')


def traduire(event):
    contents = entry.get(1.0, END)
        entry2.config(state=NORMAL)
        entry2.delete(1.0, END)
        if var.get() == "Détecter la langue":
            auto = translator.detect(contents)
            try:
                result = translator.translate(contents, src=auto.lang, dest=langue[var2.get()])
                entry2.insert(END, result.text)
            except ValueError:
                pass
        else:
            result = translator.translate(contents, src=langue[var.get()], dest=langue[var2.get()])
            entry2.insert(END, result.text)
        entry2.config(state=DISABLED)


entry.bind('<KeyRelease>', traduire)

main.mainloop()

but the function traduire is execute when I release a key but i want to execute this function only when I stopped writing text ;)

Thank you for your help !

Like jasonharper suggested in the comment, one way to execute traduire 1s after the user stopped writing text is to use after to schedule the execution of traduire in 1s and cancel this execution if another key is pressed, using after_cancel . This way, traduire will actually be executed only if the user has not pressed any key for 1s.

My suggestion is to bind <KeyRelease> to the following stop_writing function:

stop_writing_id = ''  # store id of the scheduled call to traduire

def stop_writing(event):
    global stop_writing_id
    main.after_cancel(stop_writing_id)  # cancel previous scheduling of traduire
    stop_writing_id = main.after(1000, traduire)  # wait 1s and execute traduire

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM