I am applying the following discussion in my codes
Can I make matplotlib sliders more discrete?
The following codes is to plot contour from five (slider: 0 ~ 4) .xlsx files on tkinter. Each file just contains numerical data in the matrix 12X6 such as
- I did not use
ipywidgets.wIntSlidersince fortkinterI want to usecanvas = FigureCanvasTkAgg(fig, root)andipywidgets.wIntSlidercannot work on 'fig'. - The problem comes from although the values are integer by using
valfmt='%0.0f', the slider itself is so continuous such that it cannot pinpoint on the integer values.
from tkinter import *
import tkinter.ttk as ttk
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
%matplotlib widget
from matplotlib.widgets import Slider
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
matplotlib.use('TkAgg')
root = Tk()
root.title('TEST')
root.geometry("800x800")
def plot_noise():
# ============================================Read .xlsx file=====================================
folder = r'C:\Users\Denny\Desktop\Work\test_read'
files = os.listdir(folder)
dfs = {}
for i, file in enumerate(files):
if file.endswith('.xlsx'):
dfs[i] = pd.read_excel(os.path.join(folder,file), sheet_name='Z=143', header = None, skiprows=[0], usecols = "B:M")
num = i + 1
rec = np.shape(dfs[0])
# =================================================PLOT===========================================
fig = plt.Figure()
canvas = FigureCanvasTkAgg(fig, root)
canvas.get_tk_widget().grid(row=6, column=0, columnspan=3, rowspan=3, sticky=W+E+N+S, padx=0, pady=0)
# ===============================================contourf=========================================
ax = fig.add_subplot(111)
fig.subplots_adjust(bottom=0.25)
X = np.arange(1,rec[1]+1,1)
Y = np.arange(1,rec[0]+1,1)
x , y = np.meshgrid(X,Y)
con = ax.contourf(x,y,dfs[1])
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')
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:
con = ax.contourf(x,y,dfs[ii])
ax.axis([1, 12, 1, 6])
slider_de.on_changed(update)
# =================================================GUI - Tkinter=======================================
resultButton = ttk.Button(root, text = 'show', command = plot_noise)
resultButton.grid(column=0, row=1, pady=15, sticky=W)
root.mainloop()
So when slider is at the initial values and two sides of frame (must be integer), the plot changes; however, at the other position, the plot will not change.
How to fix that? Thanks!!