0

Following is my code for control panel with 8 buttons on it.

from Tkinter import *
import ttk

class light_control(Frame):
  def __init__(self,i,parent,root,ltext,btext):
    Frame.__init__(self,parent)
    self.lc_Label = Label(self,text=ltext).pack()
    self.lc_Button = Button(self,
                text=btext,
                width=10,
                command=lambda i=i:root.toggle_button(i)
                ).pack()

class mi_control_panel(Frame):
 def __init__(self, master=Tk()):
    Frame.__init__(self, master)   
    self.master = master
    self.init_window()

 def init_window(self):
    self.grid()
    self.master.title("Control Panel")
    self.pack(fill=BOTH, expand=1)
    self.master.attributes('-zoomed', True)
    self.state = True
    self.master.attributes("-fullscreen", self.state)
    self.light_controls = []
    self.render_notebook()

 def toggle_button(self,x):
    print self.light_controls[x].lc_Button

 def render_notebook(self):
    n = ttk.Notebook(self)
    f1 = ttk.Frame(n)  
    text2 = Label(f1,text='Control Panel for Lights',relief='ridge')
    text2.grid(row=0,column=0,columnspan=4)
    for x in xrange(8):
      b = light_control(x,f1,self,"Light "+str(x),"OFF")
      self.light_controls.append(b)
    for i in xrange(1,3):
      for j in xrange(4):
        self.light_controls[4*i+j-4].grid(row=i,column=j,padx='80',pady='30')

    n.add(f1, text='Lights')
    n.grid(row=0,column=0,sticky='EW')

micp = mi_control_panel()
micp.tk.mainloop()  

My problem is, when I click a button, all I get is None. That is the function toggle_button is called but I can't access the variable lc_Button of the class light_control. What I intend to do is create a list of Buttons attached to the same callback function which identifies which button is clicked and perform action accordingly. I can print the variable x in toggle_button function. It works fine. Any guideline highly appreciated. Thanks in advance.

  • have you tried instead of using `lambda i=i:root.toggle_button(i)` this code `lambda i:root.toggle_button(i)` ? This is how I define lambda functions. – Sens4 Oct 29 '16 at 00:20
  • `lambda i: root.toggle_button(i)` gives the error `TypeError: () takes exactly 1 argument (0 given)` – Amroz Siddiqui Oct 29 '16 at 03:49

1 Answers1

0

Your problem is

elf.lc_Button = Button(...).pack()

It assigns to variable value returned by pack() which is always None

You need

elf.lc_Button = Button(...)
elf.lc_Button.pack()

BTW: you have the same mistake with Label

self.lc_Label = Label(...).pack()

so if you will need to use self.lc_Label then you need

self.lc_Label = Label(...)
self.lc_Label.pack()
furas
  • 134,197
  • 12
  • 106
  • 148
  • It worked. Thank you very much. Apologies for giving you the trouble. And I am embarrassed for overlooking such a simple thing. – Amroz Siddiqui Oct 29 '16 at 04:44