tkinter - 检查文本小部件是否为空 [英] tkinter - check if Text widget is empty

查看:39
本文介绍了tkinter - 检查文本小部件是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

操作系统:Windows 8.1Python 3.5

OS: Windows 8.1 Python 3.5

在 Tkinter 中

In Tkinter

我发现了大量代码来验证输入框是否为空.但是当我尝试对 Text 小部件应用相同的方法时,它不起作用.看起来文本小部件有一个 \n 字符,这可能是问题所在.

I found plenty of code to validate if an entry box is empty. But when I try to apply same method for a Text widget it does not work. It looks like the text widget has an \n character and that might be the problem.

知道如何进行此验证吗?

Any idea of how to do this validation ?

推荐答案

Tkinter 自动在小部件中的数据末尾添加换行符.要查看小部件是否为空,请将换行符之前的索引与起始索引进行比较;如果它们相同,则小部件为空.

Tkinter automatically adds a newline at the end of the data in the widget. To see if the widget is empty, compare the index right before this newline with the starting index; if they are the same, the widget is empty.

您可以使用索引 "end-1c" (或 "end - 1 char") 来表示尾随换行符之前的字符索引.您可以使用文本小部件的 compare 方法进行比较.

You can use the index "end-1c" (or "end - 1 char") to represent the index of the character immediately before the trailing newline. You can use the text widget's compare method to do the comparison.

if text.compare("end-1c", "==", "1.0"):
    print("the widget is empty")

假设您的小部件中没有数百兆字节,您还可以获取内容并将长度与零进行比较.这会在小部件中生成数据的临时副本,在大多数情况下这应该是无害的.同样,您不想获得尾随的换行符:

Assuming you don't have hundreds of megabytes in your widget, you can also get the contents and compare the length to zero. This makes a temporary copy of the data in the widget, which in most cases should be fairly harmless. Again, you don't want to get the trailing newline:

if len(text.get("1.0", "end-1c")) == 0:
    print("the widget is empty")

这篇关于tkinter - 检查文本小部件是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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