Label is the most popular Component in Tkinter framework as it is the most useful element that communicates any textual message.
Label is a class, we instantiate it and pass some arguments to transform its behavior. We add style as if we are using css, we can also change font and its weight.
from tkinter import * window = Tk() my_label = Label(window, text = "My first app") my_label.pack() window.mainloop()
my_label is a variable that refence the instance of the Label, unless you will not access the object in the future then you don't need an identifier for it. Hence getting rid of the call to .pack() is necessary because of the absence of reference variable for the object.
In that case we may write it as follow.
my_label = Label(window, text = "My first app").pack()
The first argument indicates the parent of the object, in that case window. If the window has a Frame and you want pack the widget in side the frame, then you mention the frame's identifier as the parent(master).
The second argument is the actual text to display on the window, and is enclosed inside double quotes.
"pack()" is a geometry manager method which makes widget appears on the screen, the other two are grid() and place().
The code above will output the following result.
The tkinter has some number of arguments that controls the appearance of the text, change the position of the text and add some styles to it.
It specifies the exact position of the text within the size provided to the widget. The default value is CENTER, which is used to center the text within the provided space.
The background color displayed behind the text.
It is used to set the bitmap to the graphical object specified so that, the label can represent the graphics instead of text.
It represents the width of the border. The default is 2 pixels.
It tells the mouse pointer to be used when the cursor is over a widget, i.e., pirate, dot, plus, etc.
The font family, size and style of the text to use. Eg font = ("Arial", 25, "bold"), will give change the font-family to Arial, give the text size of 25 and make the text bold if available.
Changes the color of the text using names or Hexadecimal. For the colors name we use the following rule, fg = "color name", and for the Hex we use add hash sign before the color's code, fg = "#ffffff".
Sometimes we may like to add images to our apps, the image keyword accepts the PhotoImage instance which hold
s the path to the image.
If the label contains multiple lines of text, the justify keyword changes the orientation of the text . It can be set to LEFT for left justification, RIGHT for right justification, or CENTER for center justification.
Specifies the border type to use. The default value is FLAT. Others are SINKEN, RAISED and RIDGE.
We use a control variable to access or change of the text's properties, through get() mothed.
Top comments (0)