How to create a Tkinter toggle button?


Python has a rich set of libraries and modules that can be used to build various components of an application. Tkinter is another well-known Python library for creating and developing GUI-based applications. Tkinter offers many widgets, functions, and modules that are used to bring life to the application visuals. We can create button widgets to perform certain tasks in an application.

In this application, we will create a toggle button that will turn the On/ Off Night and Day mode of the application. To create a toggle button, we have to first render the image in a Label.

We define buttons and functions to change the background color of the window. Since the buttons need to be changed repeatedly, we have to declare a global variable is_on=True which helps to control the function.

Example

# Import tkinter in the notebook
from tkinter import *

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

# set Title
win.title('Toggle Button Demonstration')

# Set the Geometry
win.geometry("700x400")
win.resizable(0, 0)

# 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:
      on_.config(image=off)
      label.config(text="Day Mode is On", bg="white", fg="black")
      is_on = False
   else:
      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
win.mainloop()

Output

If we execute the above code, it will display a window that contains a toggle button.

If we click the button, it will change the color of the window.

Updated on: 18-Jun-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements