Skip to content

Commit dc4ac8a

Browse files
committed
demo of tags in text widget
1 parent 2727fcc commit dc4ac8a

File tree

1 file changed

+47
-2
lines changed

1 file changed

+47
-2
lines changed

Diff for: src/program13.py

+47-2
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,12 @@
1717
- 'end' refers to the position after the last character of a line
1818
- Please refer the indices section of tkinter documentation of Text Widget for more details
1919
20+
Tags can be created in text widget to modify words/text at various locations with some logic.
21+
Tags are mapped to the specified locations/indices of text in Text widget.
22+
So it is possible to use these tags for text modification instead of text indices.
23+
Therefore, making it convenient for programming.
24+
25+
2026
'''
2127

2228
import tkinter as tk
@@ -58,10 +64,49 @@ def __init__(self, master):
5864
self.btn8 = ttk.Button(self.master, text = 'Disable Text Field', command = self.disableEnable)
5965
self.btn8.pack()
6066

61-
6267
self.lbl1 = ttk.Label(self.master, text = 'Waiting to display TEXT....')
6368
self.lbl1.pack()
64-
69+
70+
71+
self.btn9 = ttk.Button(self.master, text = 'Create tag named \'myTag\' at line 2', command = self.tagDemo)
72+
self.btn9.pack()
73+
74+
def tagDemo(self):
75+
if self.btn9['text']=='Create tag named \'myTag\' at line 2':
76+
self.btn9.config(text = 'Remove Tag')
77+
self.text.tag_add('myTag', '2.0', '2.0 lineend')
78+
79+
self.btn10 = ttk.Button(self.master, text = 'Change myTag background to yellow', command = self.tagbgyellow)
80+
self.btn10.pack()
81+
82+
self.btn11 = ttk.Button(self.master, text = 'Remove tag from 1st word of line 2', command = self.tagrm21word)
83+
self.btn11.pack()
84+
85+
self.btn12 = ttk.Button(self.master, text = 'myTag Span', command = self.getTagSpan)
86+
self.btn12.pack()
87+
88+
self.btn13 = ttk.Button(self.master, text = 'Show all Tags in Text widget', command = self.displayAllTags)
89+
self.btn13.pack()
90+
91+
else:
92+
self.btn9.config(text = 'Create tag named \'myTag\' at line 2')
93+
self.text.tag_delete('myTag')
94+
self.btn10.destroy()
95+
self.btn11.destroy()
96+
self.btn12.destroy()
97+
self.btn13.destroy()
98+
99+
def getTagSpan(self):
100+
self.lbl1.config(text = self.text.tag_ranges('myTag'))
101+
102+
def displayAllTags(self):
103+
self.lbl1.config(text = self.text.tag_names())
104+
105+
def tagrm21word(self):
106+
self.text.tag_remove('myTag', '2.0', '2.0 wordend')
107+
def tagbgyellow(self):
108+
self.text.tag_configure('myTag', background = 'yellow')
109+
65110
def randomTextEntry(self):
66111
text = '''Random Text
67112
It real sent your at.

0 commit comments

Comments
 (0)