In this video I’ll show you how to create a fun little on/off button that will switch between on and off whenever you click on it.

For this video we’ll be using two images, and on image and an off image. We’ll use those images as the background of a button.

Then we’ll create a Boolean (true/false) variable to keep track of whether the button has been clicked (True) or not (False).

Whenever we click the button we’ll call a function that will change the Boolean variable from True to False or False to True and update the
image.

Python Code: flip.py
(Github Code)

from tkinter import *

root = Tk()
root.title('Codemy.com - Flip The Switch!')
root.iconbitmap('c:/gui/codemy.ico')
root.geometry("500x300")

# Keep track of the button state on/off
global is_on
is_on = True



# Create Label
my_label = Label(root, 
	text="The Switch Is On!", 
	fg="green", 
	font=("Helvetica", 32))

my_label.pack(pady=20)


# Define our switch function
def switch():
	global is_on
	# Determin is on or off
	if is_on:
		on_button.config(image=off)
		my_label.config(text="The Switch is Off", fg="grey")
		is_on = False
	else:
		on_button.config(image=on)
		my_label.config(text="The Switch is On", fg="green")
		is_on = True

# Define Our Images
on = PhotoImage(file="images/on.png")
off = PhotoImage(file="images/off.png")

# Create A Button
on_button = Button(root, image=on, bd=0, command=switch)
on_button.pack(pady=50)

root.mainloop()

John Elder

John is the CEO of Codemy.com where he teaches over 100,000 students how to code! He founded one of the Internet's earliest advertising networks and sold it to a publicly company at the height of the first dot com boom. After that he developed the award-winning Submission-Spider search engine submission software that's been used by over 3 million individuals, businesses, and governments in over 42 countries. He's written several Amazon #1 best selling books on coding, and runs a popular Youtube coding channel.

View all posts

Add comment

Your email address will not be published. Required fields are marked *

John Elder

John is the CEO of Codemy.com where he teaches over 100,000 students how to code! He founded one of the Internet's earliest advertising networks and sold it to a publicly company at the height of...