In this lesson i want to show you How to Create Label in Python TKinter GUI, To create a label in Python TKinter GUI, you can use the Label
widget. Here is an example of creating a label and setting its text and font:
1 2 3 4 5 |
from tkinter import * root = Tk() label = Label(root, text="Hello GeeksCoders", font=("Arial", 20)) label.pack() root.mainloop() |
In this example, we first import the Tk
class from the tkinter module. Then we create a new Tkinter application by creating an instance of the Tk class. The Label
widget is then created and its text and font are set to “Hello GeeksCoders” and “Arial 20”, respectively. Finally, the pack()
method is used to place the label on the screen. The mainloop()
method is called to start the event loop and display the label on the screen.
Run the complete code and this will be the result
You can also use grid
or place
method for layout management.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Using grid layout from tkinter import * root = Tk() label = Label(root, text="Hello GeeksCoders", font=("Arial", 20)) label.grid(row=0, column=0) root.mainloop() # Using place layout from tkinter import * root = Tk() label = Label(root, text="Hello GeeksCoders", font=("Arial", 20)) label.place(x=20, y=20) root.mainloop() |
In the above example, grid layout is used to place the label on the screen and place layout is used to place the label on the specific position.
Here is an example of creating a label using Object-Oriented Programming (OOP) in Python TKinter:
1 2 3 4 5 6 7 8 9 10 11 |
import tkinter as tk class LabelApp(tk.Tk): def __init__(self): super().__init__() self.title("Label Example") self.label = tk.Label(self, text="Hello World", font=("Arial", 20)) self.label.pack() app = LabelApp() app.mainloop() |
You can also use grid
or place
layout management within the class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import tkinter as tk class LabelApp(tk.Tk): def __init__(self): super().__init__() self.title("Label Example") self.label = tk.Label(self, text="Hello World", font=("Arial", 20)) self.label.grid(row=0, column=0) app = LabelApp() app.mainloop() # or class LabelApp(tk.Tk): def __init__(self): super().__init__() self.title("Label Example") self.label = tk.Label(self, text="Hello World", font=("Arial", 20)) self.label.place(x=20, y=20) app = LabelApp() app.mainloop() |
In the above example, grid layout is used within the class to place the label on the screen and place layout is used within the class to place the label on the specific position.