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:
Flowchart:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/tkinter/python-tkinter-events-and-event-handling-exercise-2.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics