Python Forum
[Tkinter] Plotting Raster Data / TIFF files on tkinter canvas - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: GUI (https://python-forum.io/forum-10.html)
+--- Thread: [Tkinter] Plotting Raster Data / TIFF files on tkinter canvas (/thread-20731.html)



Plotting Raster Data / TIFF files on tkinter canvas - RRSCNGP - Aug-28-2019

Hi All....I have a TIFF file which I am trying to plot on the tkinter canvas using the following code:

import tkinter

from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg, NavigationToolbar2Tk)
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
import matplotlib.pyplot as plt

root = tkinter.Tk()

fig = Figure(figsize=(5, 4), dpi=100)

canvas1 = FigureCanvasTkAgg(fig, master=root)
canvas1.draw()

toolbar = NavigationToolbar2Tk(canvas1,root)
toolbar.update()
toolbar.pack(side=tkinter.TOP, fill=tkinter.X, padx=8)

canvas1.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1, padx=10, pady=5)

canvas1._tkcanvas.pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1, padx=10, pady=5)

def on_key_press(event):
    print("you pressed {}".format(event.key))
    key_press_handler(event, canvas1, toolbar)


canvas1.mpl_connect("key_press_event", on_key_press)

def _load():
    import rasterio as rio
    from rasterio.plot import show
    ax = fig.add_subplot(111)
    fig.subplots_adjust(bottom=0, right=1, top=1, left=0, wspace=0, hspace=0)

#    fig.tight_layout(pad=0)

    with rio.open(r'C:\Users\Desktop\t1.tif') as src_plot:
        show(src_plot, ax=ax, cmap='gist_gray')
    plt.close()
    ax.set(title="",xticks=[], yticks=[])
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)
    ax.spines["left"].set_visible(False)
    ax.spines["bottom"].set_visible(False)
    canvas1.draw()

button = tkinter.Button(master=root, text="Load", command=_load)
button.pack(side=tkinter.BOTTOM)

root.mainloop()
Issue which I am facing is that the raster/tiff file is getting plotted on the tkinter canvas, but it is placed inside the matplotlib figure window/frame whose size is not equal to tkinter canvas size. And hence if I am panning the figure inside the canvas, it is only moving inside the window and not across the canvas (as it used to be in ARCMAP/QGIS). Can someone help me out in resolving the issue.