Aug-31-2021, 05:40 PM
Here's the same code, but with individual functions associated with each button:
All you have to do is add the interface code:
All you have to do is add the interface code:
import tkinter as tk class BtnEngine: # rename class as you wish def __init__(self, parent): self.parent = parent self.parent.title("Tryout7") self.parent.minsize(100, 100) self.btn_row = 0 self.btn_column = 0 self.number_of_btns = 12 self.btns_per_row = 4 self.btn_number = 0 self.btns = [None] * self.number_of_btns self.dispatch() def dispatch(self): self.create_buttons() def create_buttons(self): btn_titles = ["volume up", "volume down", "channel up", "channel down", "conditioner on", "conditioner off", "raise the bed ", "lower the bed", "open television", "mute", "open curtain", "close curtain"] btn_actions = [self.volume_up, self.volume_down, self.channel_up, self.channel_down, self.conditioner_on, self.conditioner_off, self.raise_the_bed, self.lower_the_bed, self.open_television, self.mute, self.open_curtain, self.close_curtain] while self.btn_number < self.number_of_btns: if not ((self.btn_column + 1) % self.btns_per_row): self.btn_row += 1 self.btn_column = 0 self.btns[self.btn_number] = (tk.Button(self.parent, text=btn_titles[self.btn_number], padx=60, pady=20, height = 2, width = 5, command=lambda idx=self.btn_number, btitle=btn_titles[self.btn_number], bfunc=btn_actions[self.btn_number]: self.button_clicked(bfunc, btitle, idx))) self.btns[self.btn_number].grid(row=self.btn_row, column=self.btn_column) self.btn_column += 1 self.btn_number += 1 def button_clicked(self, fcntn, title, idx): fcntn(idx+1, title) def volume_up(self, idx, title): print(f"Button {idx} pressed, {title} command running") def volume_down(self, idx, title): print(f"Button {idx} pressed, {title} command running") def channel_up(self, idx, title): print(f"Button {idx} pressed, {title} command running") def channel_down(self, idx, title): print(f"Button {idx} pressed, {title} command running") def conditioner_on(self, idx, title): print(f"Button {idx} pressed, {title} command running") def conditioner_off(self, idx, title): print(f"Button {idx} pressed, {title} command running") def raise_the_bed(self, idx, title): print(f"Button {idx} pressed, {title} command running") def lower_the_bed(self, idx, title): print(f"Button {idx} pressed, {title} command running") def open_television(self, idx, title): print(f"Button {idx} pressed, {title} command running") def mute(self, idx, title): print(f"Button {idx} pressed, {title} command running") def open_curtain(self, idx, title): print(f"Button {idx} pressed, {title} command running") def close_curtain(self, idx, title): print(f"Button {idx} pressed, {title} command running") def main(): root = tk.Tk() BtnEngine(root) root.mainloop() if __name__ == '__main__': main()