Tkinter: set StringVar after event, including the key pressed

后端 未结 2 2026
后悔当初
后悔当初 2020-12-01 19:53

Every time a character is entered into a Text widget, I want to get the contents of that widget and subtract its length from a certain number (basically a \"you

2条回答
  •  南方客
    南方客 (楼主)
    2020-12-01 20:23

    A simple solution is to add a new bindtag after the class binding. That way the class binding will fire before your binding. See this answer to the question How to bind self events in Tkinter Text widget after it will binded by Text widget? for an example. That answer uses an entry widget rather than a text widget, but the concept of bindtags is identical between those two widgets. Just be sure to use Text rather than Entry where appropriate.

    Another solution is to bind on KeyRelease, since the default bindings happen on KeyPress.

    Here's an example showing how to do it with bindtags:

    import Tkinter as tk
    
    class Example(tk.Frame):
        def __init__(self, master):
            tk.Frame.__init__(self, master)
    
            self.post_tweet = tk.Text(self)
            bindtags = list(self.post_tweet.bindtags())
            bindtags.insert(2, "custom") # index 1 is where most default bindings live
            self.post_tweet.bindtags(tuple(bindtags))
    
            self.post_tweet.bind_class("custom", "", self.count)
            self.post_tweet.grid()
    
            self.char_count = tk.Label(self)
            self.char_count.grid()
    
        def count(self, event):
            current = len(self.post_tweet.get("1.0", "end-1c"))
            remaining = 140-current
            self.char_count.configure(text="%s characters remaining" % remaining)
    
    if __name__ == "__main__":
        root = tk.Tk()
        Example(root).pack(side="top", fill="both", expand=True)
        root.mainloop()
    

提交回复
热议问题