为了账号安全,请及时绑定邮箱和手机立即绑定

验证 tkinter 文本小部件

验证 tkinter 文本小部件

弑天下 2023-10-11 21:22:10
我正在 Tkinter 中开发一个简单的文本编辑器。我想在用户输入文本时验证文本小部件,以便可以应用样式。我无法绑定,<KeyPress>因为它在按下按键后更新,并且我无法绑定<KeyRelease>,因为当用户按住按键时它不会触发事件,而这是它需要的。还有其他办法解决这个问题吗?这是最小的代码:import tkinter as tkclass 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()
查看完整描述

1 回答

?
慕慕森

TA贡献1856条经验 获得超17个赞

我可以通过简单地将<KeyRelease>和绑定<KeyPress>到tk.Text小部件来实现它。(虽然我按照bindings指定的相同顺序进行了操作,但我认为这不会产生影响)。


现在我不能说这是一个好的解决方案还是一个好的实践,但它确实有效。


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


查看完整回答
反对 回复 2023-10-11
  • 1 回答
  • 0 关注
  • 48 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信