Python Tkinter - Label

Pybeginner
By -
0



To add a label in tkinter, the Label class is used, and the syntax is shown below:

syntax

 

label = Label(window, text = "Hello")

 

The Label class, takes some attributes, such as text , heightwidthcolor, etc.

In the syntax, theparameter window represents, the screen on which the label will be placed, and theparameter text represents the text that will be displayed on this Label.

Next, we will define its position in the window using the grid function and provide the location as follow:

 

label.grid (column = 0, row = 0)


Therefore, the complete code will look like this:

 

from tkinter import *

window = Tk ()
window. title ("Tkinter Label")
window.geometry ('250x250')

label = Label (window, text = "First label")
label.grid (column = 0, row = 0)

window.mainloop ()

 



Every time we are going to create a label we must always use one of the place, pack or grid geometry managers.

Without calling the place, pack or grid function for the label, it will not be displayed.

 

Python Tkinter Label - how to define the font size of the Label 

 

You can set the font of the label to make it larger and perhaps bold. You can also change the font style. To do this, you can pass the font parameter like this:

label = Label (window, text = "First label", font = ("Arial Bold", 30))
label.grid (column = 0, row = 0)

 

Therefore, the complete code will look like this:

from tkinter import *

window = Tk()
window. title("Tkinter Label")
window.geometry ('250x250')

label = Label(window, text = "First label", font=("Arial Bold", 30))
label.grid(column = 0, row = 0)

window.mainloop()

 



 

Python Tkinter Label - how to define the color of the letter and the background of the Label 

 

You can define the color of the letter that will be displayed on the label, or even the color of the background of the label.

See the example below.

 

from tkinter import *

window = Tk()
window. title("Tkinter Label")
window.geometry('250x250')

label = Label(window, text = "First label", font = ("Arial Bold", 20))
label.grid (column = 0, row = 0)

label1 = Label(window, text="Second label", width=10, height=1, font=("Arial Bold", 20), fg = 'green', bg = 'white')
label1.grid(column=0, row=1)

label2 = Label(window, text="Third label", width=8, height=2, font=("Arial Bold", 20) , fg = 'white', bg = 'black')
label2.grid(column=0, row=2)


window.mainloop()

 



 

fg - used for the color of the letter, in this case it was set to green;

bg - used for the background color, in this case it was set to white.


Post a Comment

0Comments

Post a Comment (0)