CodingNic

GUI Development

Buttons and Labels

GUI Development 38 min read

Buttons and Labels

Buttons and Labels

A window becomes useful when it shows information and lets users interact.

Two of the most common Tkinter widgets are:

  • Label
  • Button

You will use them in almost every GUI app.


What Is a Label?

A label displays text in the window.

Examples:

  • Welcome messages
  • Instructions
  • Titles
  • Results

Create a Label

python
import tkinter as tk

window = tk.Tk()

label = tk.Label(window, text="Hello World")
label.pack()

window.mainloop()

What This Does

tk.Label()

Creates a label widget.

text="Hello World"

The text shown to the user.

pack()

Places the widget inside the window.


Change Label Style

python
label = tk.Label(
    window,
    text="Welcome",
    font=("Arial", 18),
    fg="blue"
)
label.pack()

font

Controls text style and size.

fg

Text color.


What Is a Button?

A button is clicked to perform an action.

Examples:

  • Submit
  • Save
  • Login
  • Calculate

Create a Button

python
button = tk.Button(window, text="Click Me")
button.pack()

Button with Action

Buttons become powerful when they run a function.

python
import tkinter as tk

def say_hello():
    print("Hello")

window = tk.Tk()

button = tk.Button(
    window,
    text="Click Me",
    command=say_hello
)
button.pack()

window.mainloop()

When clicked, it prints:

text
Hello

Update Label with Button

python
import tkinter as tk

def change_text():
    label.config(text="Button Clicked")

window = tk.Tk()

label = tk.Label(window, text="Ready")
label.pack()

button = tk.Button(window, text="Press", command=change_text)
button.pack()

window.mainloop()

config()

Used to change widget settings after creation.

Example:

  • text
  • color
  • size

Style a Button

python
button = tk.Button(
    window,
    text="Save",
    bg="green",
    fg="white",
    width=10
)

Common Beginner Errors

Missing pack()

Widget may not appear.

Using command=say_hello()

Wrong:

python
command=say_hello()

Correct:

python
command=say_hello

Do not use parentheses.

Function Defined After Button

Define functions before using them.


Code Along

Build a window with:

  • label = Welcome
  • button = Change

When button is clicked, label becomes Updated.


Mini Challenge

Create:

  • label text = 0
  • button text = Add

Each click increases the number by 1.

Expected result:

0 → 1 → 2 → 3


Real World Use Case

Labels and buttons are used in forms, dashboards, calculators, and settings windows.


Quiz

  1. What does a label do?
  2. What does a button do?
  3. Why is pack() needed?
  4. Why do we use command=function_name without parentheses?

Assignment

Create a GUI with two buttons:

  • Green button changes label to Success
  • Red button changes label to Error

Summary

You learned how to create labels and buttons, connect button clicks to functions, and update GUI text dynamically.