On/Off Toggle Button Switch in Tkinter


Tkinter provides features for adding different kinds of widgets necessary for an application. Some of these widgets are: Button widget, Entry Widget, Text Box, Slider, etc. In this article, we will see how we can create an application with a button such that it can either be on or off.

In this example, we will use these two buttons for demonstration,


# Import tkinter in the notebook
from tkinter import *

# Create an instance of window of frame
win =Tk()

# set Title
win.title('On/Off Demonstration')

# Set the Geometry
#Create a variable to turn on the button initially
is_on = True

# Create Label to display the message
label = Label(win,text = "Night Mode is On",bg= "white",fg ="black",font =("Poppins bold", 22))
label.pack(pady = 20)

# Define our switch function
def button_mode():
   global is_on
   #Determine it is on or off
   if is_on:
      label.config(text ="Day Mode is On",bg ="white", fg= "black")
      is_on = False
      on_.config(image = on)
      label.config(text ="Night Mode is On", fg="black")
      is_on = True

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

# Create A Button
on_= Button(win,image =on,bd =0,command = button_mode)
on_.pack(pady = 50)

#Keep Running the window


Running the above code will create a Button to operate on/off mode.

If you click the button, it will change as follows −

Updated on 06-Mar-2021 08:55:37