menator01
King Coder
Python:
#! /usr/bin/env python3
# Do the imports
import tkinter as tk
from functools import partial
import os
# Get current working directory
img_dir = os.getcwd()
img_dir = f'{img_dir}'
# Create the window class
class MyClass:
def __init__(self, parent):
# Set some parent variables
self.parent = parent
self.parent.columnconfigure(0, weight=1)
self.parent.rowconfigure(0, weight=1)
# Create a frame to hold images
self.frame = tk.Frame(self.parent)
self.frame.grid(column=0, row=0, sticky='news')
self.frame.grid_columnconfigure(0, weight=3)
self.frame.grid_rowconfigure(0, weight=3)
# Get the images
bulb = tk.PhotoImage(file=f'{img_dir}/light_off.png')
bulb.img = bulb
switch = tk.PhotoImage(file=f'{img_dir}/switch_off.png')
switch.img = switch
# Create a label to hold the images
self.light = tk.Label(self.frame, image=bulb, bg='black')
self.light.grid(column=0, row=0, sticky='news')
self.switch = tk.Label(self.frame, image=switch)
self.switch['cursor'] = 'hand2'
self.switch.grid(column=0, row=1, sticky='news')
# Set is_clicked to True
is_clicked = True
# Bind the switch to LMB
self.switch.bind('<ButtonRelease-1>', partial(self.lightswitch, is_clicked))
# Define the function that changes the images and their state
def lightswitch(self, value, event):
is_clicked = True
if value:
bulb = tk.PhotoImage(file=f'{img_dir}/light_on.png')
bulb.img = bulb
self.light['image'] = bulb
switch = tk.PhotoImage(file=f'{img_dir}/switch_on.png')
switch.img = switch
self.switch['image'] = switch
self.is_clicked = False
self.switch.bind('<ButtonRelease-1>', partial(self.lightswitch, self.is_clicked))
else:
bulb = tk.PhotoImage(file=f'{img_dir}/light_off.png')
bulb.img = bulb
self.light['image'] = bulb
switch = tk.PhotoImage(file=f'{img_dir}/switch_off.png')
switch.img = switch
self.switch['image'] = switch
self.is_clicked = True
self.switch.bind('<ButtonRelease-1>', partial(self.lightswitch, self.is_clicked))
def main():
root = tk.Tk()
root.title('Light On/Off')
root.geometry('+250+200')
MyClass(root)
root.mainloop()
if __name__ == '__main__':
main()
images




Last edited: