Jan-16-2022, 05:19 AM
The way I used grid was a hack to make the code look more like the guizero code. Had I started with tkinter I would probably have the button helper function set the grid position and set any padding.
import tkinter as tk path = "" class RelayButton(tk.Button): """A button that toggles a relay""" def __init__(self, parent, url="", on_image=None, off_image=None, **kwargs): super().__init__(parent, image=off_image, command=self.toggle) self.url = url self._on = False self.on_image = on_image self.off_image = off_image @property def on(self): """Return state of the relay""" return self._on @on.setter def on(self, on): """Set state of the relay""" self._on = on if on: # requests.post(f"{self.url}cm?cmnd=Power On") self["image"] = self.on_image else: # requests.post(f"{self.url}cm?cmnd=Power Off") self["image"] = self.off_image def toggle(self): """Toggle state of the relay""" self.on = not self.on def new_button(name, url, parent, row, column, **kwargs): """Convenience functon that creates a RelayButton""" on_image = tk.PhotoImage(file=f"{path}{name}_on.png") off_image = tk.PhotoImage(file=f"{path}{name}_off.png") button = RelayButton(parent, url, on_image, off_image, **kwargs) button.grid(row=row, column=column, padx=5) return button def main(): app = tk.Tk() buttons = [ new_button('living_room', "http://192.168.0.101/", app, 0, 0), new_button('kitchen', "http://192.168.0.113/", app, 0, 1)) ] for b in buttons: b.on = False app.mainloop() if __name__ == "__main__": main()