-1

I'm trying to set up a list of checkbuttons from top to bottom in the GUI and add up the associated "onvalues" for each of the checkbuttons that are on.

My problem now is that for some reason my 'command' attribute in my 'calcbutton' is giving me a "Name 'calc_cost' is not defined" error.

I've added a bunch of imports that you see at the top of the code hoping that would solve the problem, to not much avail.

import tkinter as tk
from tkinter import *
from tkinter import Button
servicelist = ("Oil change","Lube job","Radiator flush","Transmission flush","Inspection","Muffler replacement","Tire rotation")
servicecost = (30,20,40,100,35,200,20)
a = 0
class Window(Frame):


    def __init__(self, master=None):
        Frame.__init__(self, master)                 
        self.master = master
        self.init_window()
    def calc_cost(self):
        print(a)

    def init_window(self):

        self.master.title("GUI")

        self.pack(fill=BOTH, expand=1)
        for i in range(len(servicelist)):
            serviceButton = Checkbutton(self, text=servicelist[i], onvalue = servicecost[i], var = a)
            serviceButton.place(x=0, rely = i*.1)
        calcButton = tk.Button(self, text = "Calculate Cost", fg = "black", bg = "green", command = calc_cost)
        calcButton.pack(side = "bottom")

root = Tk()

#size of the window
root.geometry("400x300")

app = Window(root)
root.mainloop()  

The checkbuttons pop up and the GUI works for the most part besides the displaying of the 'calcbutton' as well as getting the "NameError: name 'calc_cost' is not defined"

Talha
  • 524
  • 1
  • 6
  • 22
  • Possible duplicate of [How do I pass a method as a parameter in Python](https://stackoverflow.com/questions/706721/how-do-i-pass-a-method-as-a-parameter-in-python) – ivan_pozdeev May 09 '19 at 00:53

1 Answers1

1

Change command = calc_cost to command = self.calc_cost

self represents the instance of the class. By using the self keyword we can access the attributes and methods of the class in python.

It will give you this output

enter image description here

gameon67
  • 3,981
  • 5
  • 35
  • 61