0

I am trying to embed a Seaborn Barplot in a new window in Tkinter using Toplevel and Canvas and following the example provided here.

However, when I run it, I get the following error:

File "", line 334, in bar_chart canvas = FigureCanvasTkAgg(figure, master=newwindow) NameError: name 'figure' is not defined

This is strange because the name 'figure' is defined.

Here is my code:

import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
from tkinter import ttk
from tkinter.ttk import *
from matplotlib.figure import Figure 
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg,  
NavigationToolbar2Tk) 
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
import seaborn as sns
import json
import re
import io

class my_program():
    def __init__(self):
        self.window = tk.Tk()
        self.window.title("My Program")
        self.create_widgets()


    def create_widgets(self):
        # Create some room around all the internal frames
        self.window['padx'] = 5
        self.window['pady'] = 5

# Graph plotting functions
        def bar_chart():
            #try:
            global graph
            global bar_chart_df
            global clean_df
            global figure
                
            newwindow = tk.Toplevel(self.window)
            newwindow.title('Bar Chart')
            newwindow.geometry('1000x700')
            
            canvas = FigureCanvasTkAgg(figure, master=newwindow)
            canvas.draw()
            canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
            
            toolbar = NavigationToolbar2Tk(canvas, newwindow)
            toolbar.update()
            canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
    
            backup()
            #except:
                #my_error = tk.messagebox.showerror(title="Try again", message="Please load a valid dataset")
                
        def bar():
            global graph
            global bar_chart_df
            global clean_df
            global figure
            
            bar_chart_df = clean_df.groupby([clean_df['VIOLATION DESCRIPTION']])['FACILITY NAME'].count().reset_index(name='No. Establishments').sort_values(by='No. Establishments',ascending=False)

            sns.barplot(y='VIOLATION DESCRIPTION', x='No. Establishments', data=bar_chart_df)
            plt.title('No. of Establishments committed violations')
            figure = Figure(figsize=(1, 2), dpi=300, facecolor='w', edgecolor='k')
            
            return figure

# button
button_label = ttk.Label(entry_frame, text="Plot Bar Chart")
button_label.grid(row=7, column=1, sticky=tk.W)

my_button = tk.Button(entry_frame, text="Plot it!", command=bar_chart)
my_button.grid(row=8, column=1, sticky=tk.W)


# Create the entire GUI program
program = my_program()

# Start the GUI event loop
program.window.mainloop()

What can it be?

0 Answers0