Home > Net >  How to embed contourf into tkinter?
How to embed contourf into tkinter?

Time:12-28

We have some discussions about embedding a matplotlib with slider in tkinter

Python: Embed a matplotlib plot with slider in tkinter properly

The key part is the following codes

import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
matplotlib.use('TkAgg')

root = Tk.Tk()
root.title("Embedding in TK")
fig = plt.Figure()                       
canvas = FigureCanvasTkAgg(fig, root)     
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

My question focuses on 'contourf'.

X = np.arange(1,5,1)
Y = np.arange(1,5,1)
x , y = np.meshgrid(X,Y)  
z = [
    [0, 0, 0, 0],
    [0, 1, 1, 0],
    [0, 1, 1, 0],
    [0, 0, 0, 0],
    ]    
conto = plt.contourf(x,y,z)
canvas = FigureCanvasTkAgg(conto,root)
canvas.get_tk_widget().grid(column=0, row=1, pady=15, sticky=tk.W)

The above is what I tried to do; however, an error popped out

AttributeError: 'QuadContourSet' object has no attribute 'set_canvas'

Is there any way for 'contourf', like canvas, such that we can embed contourf into tkinter?

CodePudding user response:

Here is a working example mixed between the offical exampel of matplot in tkinter and a random youtube video. It works fine for me:

import tkinter as tk
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
matplotlib.use('TkAgg')

root = tk.Tk()
root.title("Embedding in TK")

fig = plt.Figure()                       
canvas = FigureCanvasTkAgg(fig, root)     
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

ax = fig.add_subplot(111)
u = np.linspace(-1,1,100)
x,y = np.meshgrid(u,u)
z = x**2   y**2
ax.contourf(x,y,z)
  • Related