

import tkinter as tk
my_w = tk.Tk()
my_w.geometry("400x300") # Size of the window
colour_night='lightgreen' # Change the night colour
colour_day='blue' # change the day colour
my_w.configure(background=colour_day) # default background of window
my_img_on = tk.PhotoImage(file = "D:\\testing\\on-off-on.png")
my_img_off = tk.PhotoImage(file = "D:\\testing\\on-off-off.png")
def my_upd():
if(b1['bg']==colour_day):
b1.config(image=my_img_on,bg=colour_night,activebackground=colour_night)
my_w.configure(background=colour_night)
else:
b1.config(image=my_img_off,bg=colour_day,activebackground=colour_day)
my_w.configure(background=colour_day)
b1=tk.Button(my_w,image=my_img_off,
relief='flat',bg=colour_day,command=lambda:my_upd())
b1.grid(row=1,column=1,padx=20,pady=10)
my_w.mainloop() # Keep the window open
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("400x300") # Size of the window
colour_night='lightgreen' # Change the night colour
colour_day='blue' # Change the day colour
my_w.configure(background=colour_day) # Default background of window
- tkinter Import: The code imports the Tkinter module, which provides tools to create GUIs in Python.my_img_on = tk.PhotoImage(file = "D:\\testing\\on-off-on.png")
my_img_off = tk.PhotoImage(file = "D:\\testing\\on-off-off.png")
- Image Files: Two images are loaded from the specified file paths using PhotoImage. my_img_on represents the "on" image, while my_img_off represents the "off" image.
def my_upd():
if(b1['bg']==colour_day):
b1.config(image=my_img_on,bg=colour_night,activebackground=colour_night)
my_w.configure(background=colour_night)
else:
b1.config(image=my_img_off,bg=colour_day,activebackground=colour_day)
my_w.configure(background=colour_day)
- my_upd() Function: This function toggles between the "day" and "night" states:b1=tk.Button(my_w,image=my_img_off,
relief='flat',bg=colour_day,command=lambda:my_upd())
b1.grid(row=1,column=1,padx=20,pady=10)
- Button Creation: The button b1 is created with the initial image my_img_off and a flat relief (button style). The background color is set to colour_day.my_w.mainloop() # Keep the window open
- mainloop(): The Tkinter main loop keeps the window open and listens for user interaction.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.