Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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,
Example
# 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
win.geometry("600x400")
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
Running the above code will create a Button to operate on/off mode.

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

Advertisements