Python Forum
tkinter lightswitch
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
tkinter lightswitch
#2
I like it, I've done another version of it by creating a BoolImageLabel that keeps track of its own state and its own images.
import tkinter as tk


class SwitchApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.title('Light On/Off')
        self.geometry('+250+200')
        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)

        self.frame = tk.Frame(self)
        self.frame.grid(column=0, row=0, sticky='news')
        self.frame.grid_columnconfigure(0, weight=3)
        self.frame.grid_rowconfigure(0, weight=3)

        self.light = BoolImageLabel('off.png', 'on.png', self.frame)
        self.light.grid(column=0, row=0, sticky='news')

        self.switch = BoolImageLabel(
            'switch_off.png', 'switch_on.png', self.frame)
        self.switch.grid(column=0, row=1, sticky='news')
        self.switch.bind('<Button-1>', self.on_switch_click)

    def on_switch_click(self, event):
        self.switch.toggle_state()
        self.light.state = self.switch.state


class BoolImageLabel(tk.Label):
    def __init__(self, false_image_path, true_image_path, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._state = False
        self._images = {False: false_image_path, True: true_image_path}
        self._set_image()

    def _set_image(self):
        self.photo_image = tk.PhotoImage(file=self._images[self.state])
        self.config(image=self.photo_image)

    def toggle_state(self):
        self.state = not self.state

    @property
    def state(self):
        return self._state

    @state.setter
    def state(self, state):
        self._state = state
        self._set_image()


if __name__ == '__main__':
    switch_app = SwitchApp()
    switch_app.mainloop()
Reply


Messages In This Thread
tkinter lightswitch - by menator01 - May-11-2021, 06:52 PM
RE: tkinter lightswitch - by Yoriz - May-11-2021, 09:42 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020