How to Justify Text in a Label

How to justify text in a label

This is an implementation of the solution proposed by TaW. It is just the base code for the implementation - no automatic re-adjustments, etc.

public void Justify(System.Windows.Forms.Label label)
{
string text = label.Text;
string[] lines = text.Split(new[]{"\r\n"}, StringSplitOptions.None).Select(l => l.Trim()).ToArray();

List<string> result = new List<string>();

foreach (string line in lines)
{
result.Add(StretchToWidth(line, label));
}

label.Text = string.Join("\r\n", result);
}

private string StretchToWidth(string text, Label label)
{
if (text.Length < 2)
return text;

// A hair space is the smallest possible non-visible character we can insert
const char hairspace = '\u200A';

// If we measure just the width of the space we might get too much because of added paddings so we have to do it a bit differently
double basewidth = TextRenderer.MeasureText(text, label.Font).Width;
double doublewidth = TextRenderer.MeasureText(text + text, label.Font).Width;
double doublewidthplusspace = TextRenderer.MeasureText(text + hairspace + text, label.Font).Width;
double spacewidth = doublewidthplusspace - doublewidth;

//The space we have to fill up with spaces is whatever is left
double leftoverspace = label.Width - basewidth;

//Calculate the amount of spaces we need to insert
int approximateInserts = Math.Max(0, (int)Math.Floor(leftoverspace / spacewidth));

//Insert spaces
return InsertFillerChar(hairspace, text, approximateInserts);
}

private static string InsertFillerChar(char filler, string text, int inserts)
{
string result = "";
int inserted = 0;

for (int i = 0; i < text.Length; i++)
{
//Add one character of the original text
result += text[i];

//Only add spaces between characters, not at the end
if (i >= text.Length - 1) continue;

//Determine how many characters should have been inserted so far
int shouldbeinserted = (int)(inserts * (i+1) / (text.Length - 1.0));
int insertnow = shouldbeinserted - inserted;
for (int j = 0; j < insertnow; j++)
result += filler;
inserted += insertnow;
}

return result;
}

In action:

Demo

How do I align my text in a label to the right side?

Try setting AutoSize to false (that makes a fixed size box). Then you can use the TextAlign property to align the text - e.g. use MiddleRight. That should do the trick.

How to make Tkinter.Label justify correctly

The proper way to have the text in a label aligned to the left of the widget is with the anchor attribute. A value of "w" (or by using the Tkinter constant W) stands for "west".

LookupOutput = Tkinter.Label(UI,textvariable=User,anchor=Tkconstants.W)

The justify attribute only affects text that wraps.

If that isn't working, the problem might not be with the text in the label. It might be that your label doesn't occupy the space you think it does. An easy way to check this is to give the label a distinctive background color so that you can distinguish the label from its parent.

I notice that you aren't using the sticky attribute when you call grid -- that may also cause problems. By default grid will align a widget in the center of the space allocated to it. If you want it to "stick" to the left side of the space that was given to it, use sticky="w" (or, again, use the Tkinter constant).

how to justify a text in a label in python?

You can add the justify parameter to the label. The default value is centre if it is not included

label = Label(canvas,anchor='w', font=("Courier", 20), compound=RIGHT,bg='white',bd=4, justify="left")

The below link goes into more depth on the label widget
https://www.tutorialspoint.com/python/tk_label.htm

How to change text justification in Matplotlib labels?

Matplotlib text commands, such as for labels and annotations, support a number of keyword arguments that affect alignment, orientation, spacing, font, etc. The full list of text properties can be found in the documentation. In the above example

axes.set_ylabel('This is an\nexample plot', rotation=0, horizontalalignment='left')

would do the trick.

As noted in the other answer, this particular example is an abuse of the y-axis label. But the general principle is the same for all kinds of Matplotlib labels.

How to align label text (multi-language) in a single line justified above the input box

Use flex and justify-content: space-between for alignment:

* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Montserrat', sans-serif;
}

p {
margin: 0px;
}

.d-flex{
width: max-content;
}
.text {
display: flex;
justify-content: space-between;
font-size: 14px;
font-weight: 600;
}

::placeholder {
font-size: 14px;
font-weight: 600;
}
<div class="d-flex flex-column">
<div class="text">
<p>Customer Name</p>
<p>الاسم</p>
</div>
<input class="form-control mb-3" type="text" placeholder="Customer Name" name="name" required>
</div>

How to justify text in center in gtk label in C

You should the vexpand property to make the label fill the free vertical space. See the working sample:

#include <gtk/gtk.h>

int main (int argc, char *argv[])
{
GtkWidget *window, *grid, *label;

gtk_init (&argc, &argv);

window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "App Sample");
gtk_window_set_default_size (GTK_WINDOW (window), 600, 400);

grid = gtk_grid_new ();
gtk_container_add (GTK_CONTAINER (window), grid);

label = gtk_label_new ("Linux is a Unix-like computer operating system ");
gtk_grid_attach (GTK_GRID (grid), label, 0, 0, 1, 1);

gtk_widget_set_vexpand (label, TRUE);
gtk_widget_set_hexpand (label, TRUE);

gtk_widget_show_all (window);

gtk_main ();

return 0;
}

Sample screenshot

But as José Fonte asked, why are you using a Grid when you only have a label? Probably to make the question simpler, but out of its original context, the grid seems bloat.

I'd recommend Glade to create the UI, your code will be cleaner and you'll easily put your UI together without fighting the API and wasting hours in a try-compile-assert-repeat cycle. GtkInspector is also of great help.



Related Topics



Leave a reply



Submit