0

For my old problem (Python) tkinter figures (with colorbar) overlap when using slider (I add bounty to this problem):

I tried to solve it by considering the following good suggestion:

tkinter figure (with colorbar) shrinks every time it's displayed

However, the new problem popped out. I rewrote the update() function as the following

def update(val):
    num_on_slider.append(slider_de.val)
    for ii in range(0,num):
        if num_on_slider[-1] == ii:
                global cbar    # <-------- new
                if cbar:       # <-------- new
                    cbar.remove()       # <-------- new
                    con = ax.contourf(x,y,dfs[ii], levels = levels, cmap=cm.jet, alpha = 0.5, antialiased = True)
                    cbar = fig.colorbar(con,ax = ax)
                    ax.axis([1, 12, 1, 6])

No overlap; however, the graph will not change as I move the slider.
It looks like the condition if cbar: block the following part of codes being executed.

But in my original problem, I assign cbar outside the function

    cbar = fig.colorbar(con,ax = ax)
    ax.axis([1, 12, 1, 6])
    # ================================================Slider==========================================
    global slider_de
    slider_bar = fig.add_axes([0.12, 0.1, 0.78, 0.03])     
    slider_de = Slider(slider_bar, 's_bar', 0, num-1, valinit=1,valfmt='%0.0f',  valstep=1)
    num_on_slider = []

    def update(val):
        num_on_slider.append(slider_de.val)
        for ii in range(0,num):
            if num_on_slider[-1] == ii:
                    global cbar
                    if cbar:
                        cbar.remove()
                        con = ax.contourf(x,y,dfs[ii], levels = levels, cmap=cm.jet, alpha = 0.5, antialiased = True)
                        cbar = fig.colorbar(con,ax = ax)
                        ax.axis([1, 12, 1, 6])
                
    slider_de.on_changed(update)          

So the value of cbar should not be None.

How to fix the problem?

Thanks!

Denny
  • 223
  • 2
  • 15
  • 1
    It seems like you created a range for the color bar that covers all possible frequencies from the five worksheets. If that is true, just call the color bar initially, remove the call to cbar from the update entirely. – Kat Jan 03 '22 at 04:30
  • @Kat You solve my original problem also. Thanks! – Denny Jan 03 '22 at 05:25

0 Answers0