Search code examples
pythontkinterheightframes

How to create two frames (top and bottom) that have the same height, using Tkinter?


In Tkinter Python, I want to create two frames and place one on top of the other, and then insert a matplotlib plot inside each of these two frames. That, I managed to do. The problem is that, when created, these two frames always seem to have different heights (the bottom one is always smaller than the top one).

My goal is to get the two frames to have the same height.

Here's a simplified version of the code that produces the said undesirable result :

import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
import numpy as np

# Root
root = tk.Tk()
root.state('zoomed')

# Upper frame 
canv = tk.Frame(root)
canv.pack()

plt.rcParams["axes.prop_cycle"] = plt.cycler(color=["#4C2A85", "#BE96FF", "#957DAD", "#5E366E", "#A98CCC"])
plt.style.use('ggplot')

L = [i for i in range(10)]

fig, ax = plt.subplots()
l = ax.fill_between(L, L)
ax.set_title("Upper plot")

canvas = FigureCanvasTkAgg(fig, canv)
canvas.draw()
canvas.get_tk_widget().pack()

# Lower frame 
canv2 = tk.Frame(root)
canv2.pack()

fig2, ax2 = plt.subplots()
l2 = ax2.fill_between(L, L)
ax2.set_title("Lower plot")
    
canvas2 = FigureCanvasTkAgg(fig2, canv2)
canvas2.draw()
canvas2.get_tk_widget().pack()

root.mainloop

Thanks to anyone willing to help.


Solution

  • Different idea: create one FigureCanvasTkAgg but two axis

    fig, (ax1, ax2) = plt.subplots(2)
    

    and matplotlib will control size.

    import tkinter as tk
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    import matplotlib.pyplot as plt
    import numpy as np
    
    root = tk.Tk()
    #root.state('zoomed')
    
    plt.rcParams["axes.prop_cycle"] = plt.cycler(color=["#4C2A85", "#BE96FF", "#957DAD", "#5E366E", "#A98CCC"])
    plt.style.use('ggplot')
    
    L = [i for i in range(10)]
    
    fig, (ax1, ax2) = plt.subplots(2)
    
    canvas = FigureCanvasTkAgg(fig, root)
    canvas.draw()
    canvas.get_tk_widget().pack(fill='both', expand=True)
    
    l1 = ax1.fill_between(L, L)
    ax1.set_title("Upper plot")
    
    l2 = ax2.fill_between(L, L)
    ax2.set_title("Lower plot")
    
    fig.tight_layout()  # suggestion from @Zakaria comment
    
    root.mainloop()