Search code examples
pythonmatplotlibtkintercanvasfigure

confusion over Tkinter terminology


I am confused over the difference between the root window, a figure, backends and the canvas when building Tkinter GUI's. As far as I can tell the canvas is something the Artist can draw on and is attached to a figure. This was helpful but I couldn't get my head around what the differences or hierarchy of window/fig/backends and canvas are: http://www.aosabook.org/en/matplotlib.html


Solution

  • You start with the window.

    window = Tk()
    

    Typically people call the window root, but it can be assigned to any variable name. The canvas object has to have an associated window object.

    my_canvas = Canvas(window)
    

    The canvas widget is a representation of a drawing space, so it has different methods that allow for editing it as such. The window can only have widgets added to it.

    I'm not that familiar with matplotlib, but it appears to be its own thing that has been made to interface with Tkinter.

    from tkinter import *
    import matplotlib.pyplot as plt  
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    
    window = Tk()
    my_figure = plt.Figure()
    chart = FigureCanvasTkAgg(my_figure, window)
    

    As you can see to easily include a matplotlib figure in a Tkinter window you have to create a special Canvas object that is both associated with the figure and the window.

    In Tkinter the hierarchy is you start with the window and add "widgets" to it. A Canvas() object is a widget; A FigureCanvasTkAgg() is an object, but it isn't a widget. A FigureCanvasTkAgg().get_tk_widget() is an object that is having a method applied to it that returns a widget that then can be used by Tkinter. A plt.Figure() is an object created from matplotlib.

    As for the architecture Tkinter is a wrapper for tcl Tk which is a cross platform toolkit for creating guis. Matplotlib uses GTK+ which is almost the same thing, but a different implementation. They are separate entities with matplotlib including a backend to bridge the gap.

    You might find this tutorial helpful. https://datatofish.com/matplotlib-charts-tkinter-gui/