Jan-29-2022, 11:32 AM
Using Yoriz's BoolImage class from this post, I made an example of using multiple image buttons with commands. the commands just turn the buttons either on or off. Could be any command or function.
#! /usr/bin/env python3 import tkinter as tk from functools import partial class BoolImage(tk.Label): def __init__(self, false_img_path, true_img_path, *args, **kwargs): super().__init__(*args, **kwargs) self._state = False self._images = {False: false_img_path, True: true_img_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() class Window: def __init__(self, parent): self.parent = parent self.btns = [] col = 0 row = 0 for i in range(15): self.btns.append(BoolImage('../images/buttons/off.png', '../images/buttons/on.png', parent)) self.btns[i].grid(column=col, row=row, sticky='news') self.btns[i]['cursor'] = 'hand2' self.btns[i]['text'] = f'Button {i}' self.btns[i]['compound'] = 'bottom' self.btns[i]['font'] = ('system', 12, 'bold') if col >= 4: col = 0 row += 1 else: col += 1 self.btns[i].bind('<Button-1>', partial(self.switch, self.btns[i])) def switch(self, btn, event): if btn.state: btn.state = False else: btn.state = True def main(): root = tk.Tk() root['padx'] = 8 root['pady'] = 4 Window(root) root.mainloop() main()
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags
Download my project scripts
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags
Download my project scripts