Henry
Henry

Reputation: 3942

Validate tkinter text widget

I am developing a simple text editor in Tkinter. I would like to validate a Text widget as the user enters text so styling can be applied. I can't bind to <KeyPress> because it updates after the key has been pressed and I can't bind to <KeyRelease> as it doesn't trigger the event when the user holds a key down, which it needs to. Is there any other way around this?
Here is the minimal code:

import tkinter as tk

class textEditor(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.textFrm = tk.Frame(self)
        self.textFrm.pack(fill = "x")
        self.text = tk.Text(self.textFrm, relief = "flat", font = ("Arial","11"))
        self.text.pack(fill = "both", expand = True)
        self.text.bind("<KeyRelease>",lambda event: self.keyPress())
        self.text.focus()
    def keyPress(self):
        #This is not called when a key is held down
        print(self.text.get("end-2c","end-1c"))

root = tk.Tk()
root.title("Text editor test")
t = textEditor(root)
t.pack()
root.mainloop()

Upvotes: 0

Views: 191

Answers (1)

P S Solanki
P S Solanki

Reputation: 1123

I was able to make it work out by simply binding both <KeyRelease> and <KeyPress> to the tk.Text widget.(although I did the bindings in the same order specified but I don't think that would make a difference).

Now I can't say if this is a good solution or a good practice, but it does the job.

import tkinter as tk

class textEditor(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.textFrm = tk.Frame(self)
        self.textFrm.pack(fill = "x")
        self.text = tk.Text(self.textFrm, relief = "flat", font = ("Arial","11"))
        self.text.pack(fill = "both", expand = True)
        self.text.bind("<KeyRelease>",lambda event: self.keyPress())
        self.text.bind("<KeyPress>",lambda event: self.keyPress())
        self.text.focus()
        
    def keyPress(self):
        print(self.text.get("end-2c","end-1c"))

root = tk.Tk()
root.title("Text editor test")
t = textEditor(root)
t.pack()
root.mainloop()

Upvotes: 1

Related Questions