验证 Tkinter.Text 小部件? [英] Validation on Tkinter.Text widget?

查看:35
本文介绍了验证 Tkinter.Text 小部件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有哪些使用 Tkinter.Text 小部件进行验证的选项?我不需要 Text 的高级功能,只需要它的多行属性.不幸的是,它缺少 textvariablevalidate 命令,所以似乎我无法附加某种回调来在每次文本更改时检查内容.我想避免绑定到 <KeyRelease>,因为它看起来可以捕获所有按键,包括 Shift、Ctrl 等键,并且看起来有点一团糟,无法正常工作.

What are my options for getting validation with the Tkinter.Text widget? I don't require Text's advanced functionality, just its multiline attribute. Unfortunately, it lacks both textvariable and validate commands, so it seems that I cannot attach some kind of callback that checks things every time the text changes. I'd like to avoid having to bind to <KeyRelease>, as that looks to capture ALL keypresses, including the likes of Shift, Ctrl, etc, keys, and would appear to be a bit of a mess to work right.

我基本上只需要检查文本字段是否为空白,并根据需要启用/禁用确定"按钮(即,如果没有文本,则禁用该按钮).

I basically just need to check if the Text field is blank or not, and enable/disable an "Ok" button as appropriate (i.e., if no text, then the button is disabled).

作为替代,有没有人遇到过 Entry 的一个不错的子类,它添加了用 Python 编写的多行功能?有 this,它将 textvariable 添加到 Text,但它是用纯 TCL 编写的,而不是 Python,而且似乎很难集成到我现有的 Python 环境中.

In lieu of this, has anyone come across a decent subclass of Entry that adds multiline functionality that is written in Python? There is this, which adds textvariable to Text, but it is written in pure TCL, not Python, and seems like it would be difficult to integrate into my existing Python environment.

推荐答案

按钮的绑定不需要乱七八糟的,不用检查值按下的键但获取小部件的内容.请记住,它的末尾总是有一个 '\n',所以当你检索内容时不要忘记丢弃它:

The binding to the <KeyRelease> button does not need to be messy, you don't have to check the value of the key pressed but fetch the content of the widget. Keep in mind that it always has a '\n' at the end, so when you retrive the contents don't forget to discard it:

content = text.get(1.0, "end-1c")

然后你只需要根据这个值改变按钮的状态:

Then you just need to change the state of the button based on this value:

import Tkinter as tk

def configure_ok_button(event):
    content = event.widget.get(1.0, "end-1c")
    state = "active" if content else "disabled"
    button.configure(state=state)

root = tk.Tk()
text = tk.Text(root)
button = tk.Button(root, text="Ok", state="disabled")
text.bind("<KeyRelease>", configure_ok_button)
text.pack()
button.pack()
root.mainloop()

这篇关于验证 Tkinter.Text 小部件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆