简体   繁体   English

使用python在Tkinter文本小部件中使用标签

[英]Working with tags in Tkinter text widget using python

I'm trying color the text in the Tkinter text widget with help of tags in this way: 我正在尝试通过标签的方式在Tkinter文本小部件中为文本着色:

text = self.text_field.get(1.0, 'end') #text_field is a text widget
s = re.findall("\d+", text)
for i in s:
    self.text_field.tag_add(i, '1.0', 'end')
    self.text_field.tag_configure(i, background='yellow', 
                                  font='helvetica 14 bold', relief='raised')

The idea is that all tags are being dynamically created, because I get numbers from text widget and they can have any length. 这个想法是所有标签都是动态创建的,因为我是从文本小部件中获取数字的,它们可以有任何长度。 This code colors all text in the widget, but I need only numbers to be colored. 此代码为小部件中的所有文本着色,但是我只需要为数字着色。

Any suggestions? 有什么建议么?

When you do 当你做

tag_add(i, '1.0', 'end')

You're making a tag that covers the whole text field. 您正在制作一个覆盖整个文本字段的标签。 You need to just add the text on the numbers, using the .start() and .stop() methods of the regex match. 您需要只需添加上的数字文本,使用.start().stop()的正则表达式匹配的方法。

There's an example for doing syntax highlighting here: 这里有一个语法高亮的例子:
http://forums.devshed.com/python-programming-11/syntax-highlighting-172406.html http://forums.devshed.com/python-programming-11/syntax-highlighting-172406.html

There is an answer to a similar question that shows how to extend the text widget to have a method that highlights text based on a regular expression. 有一个类似问题的答案,该问题显示了如何扩展文本小部件以具有一种基于正则表达式突出显示文本的方法。 For examples see How to highlight text in a tkinter Text widget 有关示例,请参见如何在tkinter文本小部件中突出显示文本

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

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