简体   繁体   English

验证 tkinter 文本小部件

[英]Validate tkinter text widget

I am developing a simple text editor in Tkinter.我正在 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.我无法绑定到<KeyPress>因为它在按下键后更新,我无法绑定到<KeyRelease>因为当用户按住键时它不会触发事件,这是它需要的。 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()

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).我能够通过简单地将<KeyRelease><KeyPress> bindingstk.Text小部件来解决这个tk.Text 。(虽然我按照指定的相同顺序进行了bindings ,但我认为这不会产生影响)。

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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