Python tkinter Label

A label represents constant text that is displayed in the frame or container. A label can display one or more lines of text that cannot be modified. A label is created as an object of Label class as:

tkinter Label

lbl = Label(f, text="Welcome to Python", width=20, height=2, font=('Courier', -30, 'bold underline'), fg='blue', bg='yellow')

Here, 'f' represents the frame object to which the label is created as a child. 'text' represents the text to be displayed. 'width' represents the width of the label in number of characters and 'height' represents the height of the label in number of lines. 'font' represents a tuple that contains font name, size and style. 'fg' and 'bg' represents the foreground and background colors for the text.

In following Program, we are creating two push buttons. We display 'Click Me' on the first button. When this button is clicked, we will display a label "Welcome to Python". This label is created in the event handler method buttonClick() that is bound to the first button. We display another button 'Close' that will close the root window upon clicking.

The close button can be created as:

b2 = Button(f, text='Close', width=15, height=2, command=quit)

Please observe the 'command' option that is set to 'quit'. This represents closing of the root window.

tkinter Label Example

A Python program to display a label upon clicking a push button.

CopiedCopy Code

from tkinter import * 
class MyButtons: 
   def __init__(self, root): 
      self.f = Frame(root, height=350, width=500) 
      self.f.propagate(0) 
      self.f.pack() 
      self.b1 = Button(self.f, text='Click Me', width=15, height=2, command=self.buttonClick) 
      self.b2 = Button(self.f, text='Close', width=15, height=2, command=quit)    
      #attach buttons to the frame 
      self.b1.grid(row=0, column=1) 
      self.b2.grid(row=0, column=2) 
      #the event handler method 
   def buttonClick(self): 
      self.lbl = Label(self.f, text="Welcome to Python", width=20, height=2, font=('Courier', 30, 'bold underline'), fg='blue') 
      self.lbl.grid(row=2, column=0)

root = Tk() 
mb = MyButtons(root) 
root.mainloop()