Bonjour à tous,

D'abord, un grand merci pour toute l'aide que j'ai déjà trouvé sur ce forum. Pour remettre rapidement les choses en perspectives, après des années de pratique de Matlab, je me lance dans des tentatives en Python. Je suis encore au stade de la compréhension rudimentaire de la programmation OO et toute remarque, tout conseil ou toute ressource est la bienvenue!

Je souhaite créer une GUI autour de scripts assez basiques mais que j’exécute quotidiennement. En gros, j'ai des data dans un excel (qui sera updaté) et je souhaite, dans un premier temps, les visualiser un peu mieux (cross section, time series, interpolation, etc).

Premier problème une fenêtre tout con pour l'instant:
- a gauche de l'écran, deux listes déroulantes pour sélectionner quoi lire dans le excel
- un bouton "lancer le dessin" a.k.a. dans mon cas, "Extraire la combination demandée"
==> Ces trois premiers éléments dans un Frame tkinter
- a droite, une fenêtre de visualisation des courbes ainsi paramétrées

Les fonctions de traitement marchent nickel, les subtilités et les manipulations du module tkinter, un peu moins...
J'ai construit mon code de la façon suivante:

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
 
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from mpl_toolkits.mplot3d import Axes3D
 
import tkinter
from tkinter import *
from tkinter.ttk import *
import tkinter.messagebox
import variables
import functions, numpy
 
# =======================
# Classes
# =======================
class master_wind(tkinter.Tk):
    def __init__(self,parent):       
        tkinter.Tk.__init__(self,parent)
        self.parent = parent
        self.initialize()
 
    def initialize(self):
        self.grid()
 
        # Setting up the UI elements
        # ====================
        fram_choice = tkinter.LabelFrame(master = self,text= 'Products',font = 'bold',bg = 'grey', width=200, height=100)
        fram_choice.grid(row = 0, column = 0, rowspan = 5)
 
        f = Figure(facecolor = 'white')
        canvas = FigureCanvasTkAgg(f, master=self)
        canvas.get_tk_widget().grid(row = 0, column = 1,rowspan = 30, columnspan = 30)
 
        sheet = functions.reading_sheets()
        txt1 = tkinter.ttk.Label(fram_choice,text= 'Select product ')
        txt1.grid(row = 0, column = 0)
        txt1.configure(anchor = tkinter.W, background = 'grey')
        listSJ = tkinter.ttk.Combobox(fram_choice, values = sheet)
        listSJ.grid(row = 1, column = 0)
        txt2 = tkinter.ttk.Label(fram_choice,text= 'Select combination ')
        txt2.grid(row = 2, column = 0)
        txt2.configure(anchor = tkinter.W, background = 'grey')
        listComb = tkinter.ttk.Combobox(fram_choice, values = variables.combination_list)
        listComb.grid(row = 3, column = 0)
        butExt = tkinter.ttk.Button(master=fram_choice, text='Extract Combination', command=lambda : self.draw_curve(canvas,f,listSJ,listComb))
        butExt.grid(row = 4, column = 0)
 
        butExit = tkinter.ttk.Button(master=self, text='Quit', command=self.close_wind)
        butExit.grid(row = 30, column = 30)
 
        self.resizable(False,False)        
 
    def close_wind(self):
        self.quit()         # stops mainloop
        self.destroy()
 
    def draw_curve(self,canvas,f,listSJ,listComb):        
        sheet = functions.reading_sheets()
 
        first = listSJ.get()
        second = listComb.get()
        # print("First Selecion is %s" %first)            
        # print("Second Selecion is %s" %second)
        indSJ, indComb = -1, -1
        if (first == ''):
            tkinter.messagebox.showwarning(title = "Warning",message = "Please select a product")
        else :         
#            for i in range(0,len(sheet)):
#                if (sheet[i] == first):
#                    indSJ = i        
            indSJ = sheet.index(first)
#            for i in range(0,len(variables.combination_list)):
#                if (variables.combination_list[i] == second):
#                    indComb = i                
            indComb = variables.combination_list.index(second)
 
            # Extracting the data
            # ====================
            dict_out = functions.data_extraction(sheet,indSJ)
            dates = dict_out["dates"]
            if (second == ''):
                tkinter.messagebox.showwarning(title = "Warning",message = "Please indicate a combination")
            else:
                dict_comb = functions.combination_extraction(indComb,dict_out["nbObs"],dict_out["nbCont"],dict_out["names"],dict_out["data_cd"])
                vectCont = numpy.arange(0,dict_comb["nbComb"])
                vectObs = numpy.arange(0,dict_comb["nbObs"])  
                ref_name = dict_comb["names"]    
                mktData = dict_comb["matrix"]
                nbObs = dict_comb["nbObs"]
                nbComb = dict_comb["nbComb"]
 
                dict_data = {"mktData":mktData,"ref_name":ref_name,"dates":dates,"vectCont":vectCont,"vectObs":vectObs,"nbObs":nbObs,"nbComb":nbComb}
 
                # Observing the surface
                # ====================
                cont_surf,obs_surf = numpy.meshgrid(vectCont,vectObs)
                mktPr_surf=[]
                for i in range(0,nbObs):
                    mktPr_surf.append(mktData[i])
 
                if (first == ''):
                    tkinter.messagebox.showwarning(title = "Warning",message = "Please select a product")            
                elif (indSJ == 0) or (indSJ == 2):
                    # Clear the content of the figure ??
                    canvas.show()
                    ax = f.add_subplot(111,projection = '3d')
                    ax.mouse_init()             
                    ax.plot_surface(cont_surf,obs_surf,mktData,cmap = cm.jet,rstride = 5,cstride = 5)                    
    #                ax.set_xticks(numpy.arange(0,nbComb,5),ref_name[0:nbComb:5])
    #                ax.set_yticks(numpy.arange(0,nbObs,5),dates[0:nbObs:5])
                    ax.set_xlabel("Contracts")
                    ax.set_ylabel("Observations")
                    ax.set_zlabel("Prices")
                    ax.plot_surface(cont_surf,obs_surf,mktData,cmap = cm.jet,rstride = 5,cstride = 5)
 
                # Adding the Button to open second windows
                # =========================================
                name_sj = sheet[indSJ]
                name_comb = variables.combination_list[indComb]
                launch_analysis = tkinter.ttk.Button(master=self, text='Open Second',  command=lambda : self.open_second_wind(name_sj,name_comb,dict_data)) 
                launch_analysis.grid(row = 30, column = 29)   
 
    def open_second_wind(self,arg1,arg2,dict_data):
        wind_stat_an = analysis_wind(None,arg1,arg2,dict_data)   # Second class for the second windows
        wind_stat_an.title("Statistical Analysis")
        wind_stat_an.configure(background = 'grey')
 
        wind_stat_an.mainloop()
 
# =======================
# Main Program
# =======================        
if __name__ =="__main__":
    wind = master_wind(None)
    wind.title("Home Page")
    wind.configure(background = 'grey')    
 
    wind.mainloop()
J'ai un problème avec ce code. En effet, lorsque j'appuie sur 'butExt' en demandant "Extract combination", rien ne s'affiche au "premier coup".
Je sais que je rentre bien dans draw_curve() puisque le bouton "Open Second" s'affiche comme je le souhaite mais je dois cliquer une deuxième fois pour voir la surface apparaître...

Au début, j'ai cru que je pouvais améliorer ce comportement en sortant la partie 'lecture des données' de la fonction de dessin à proprement parler, mais j'ai ce même problème sur des situations bien plus simples ailleurs dans le code.

Finalement, je précise que je suis conscient du caractère optimisable et brouillon de ce code, je m'en excuse mais j'aimerais vraiment comprendre d'où vient ce phénomène et comment je peux y remédier. Je pense vraiment que quelque chose m'échappe dans la logique donc je vous remercie d'avance pour toute aide, piste, exemple ou autre.

Colin