w3resource

Python Tkinter label and button example

Python Tkinter Events and Event Handling: Exercise-2 with Solution

Write a Python program using Tkinter that creates a label and a button. When the button is clicked, change the label text to "Button Clicked!".

Sample Solution:

Python Code:

import tkinter as tk
# Function to change the label text
def change_label_text():
    label.config(text="Button Clicked!")

# Create the main window
root = tk.Tk()
root.title("Label and Button Example")

# Create a label widget
label = tk.Label(root, text="Tkinter Exercises (Label Text)")
label.pack(padx=20, pady=20)

# Create a button widget
button = tk.Button(root, text="Click Me", command=change_label_text)
button.pack()

# Start the Tkinter main loop
root.mainloop()

Explanation:

In the exercise above -

  • Import the "tkinter" module.
  • Define a function "change_label_text()" function that changes the label widget text when called.
  • Create the main Tkinter window 'root' and set its title.
  • Create a label widget initially set to "Label Text" and a button widget labeled "Click Me." We associate the "change_label_text()" function with the button's command parameter.
  • Finally, start the Tkinter main loop with “root.mainloop()”, which keeps the GUI application running.

Output:

Tkinter: Python Tkinter label and button example. Part-1
Tkinter: Python Tkinter label and button example. Part-2

Flowchart:

Flowchart: Python Tkinter label and button example.

Python Code Editor:


Previous: Python Tkinter message box example.
Next: Python Tkinter simple calculator example.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.