From: cvs2git Date: Fri, 10 Oct 2008 12:49:18 +0000 (+0000) Subject: This commit was manufactured by cvs2git to create tag 'V1_14QT4v1'. X-Git-Tag: V1_14QT4v1 X-Git-Url: http://git.salome-platform.org/gitweb/?a=commitdiff_plain;h=655c56ea13f97cd95af4cc720d82b0692b81c801;p=tools%2Feficas.git This commit was manufactured by cvs2git to create tag 'V1_14QT4v1'. Sprout from BR_dev_V1_14 2008-10-10 12:49:17 UTC Pascale Noyret '*** empty log message ***' Delete: Aster/Cata/cataSTA9/Intranet/__init__.py Aster/Cata/cataSTA9/Intranet/calc_eolienne.py Aster/Cata/cataSTA9/Intranet/macr_cabri_calc_cata.py Aster/Cata/cataSTA9/Intranet/macr_cabri_calc_ops.py Aster/Cata/cataSTA9/Intranet/macr_cabri_mail_cata.py Aster/Cata/cataSTA9/Intranet/macr_cabri_mail_dat.py Aster/Cata/cataSTA9/Intranet/macr_cabri_mail_ops.py Aster/Cata/cataSTA9/Intranet/macro_bascule_schema_ops.py InterfaceTK/Interp.py InterfaceTK/TroisDPal.py InterfaceTK/__init__.py InterfaceTK/appli.py InterfaceTK/basestyle.py InterfaceTK/browser.py InterfaceTK/bureau.py InterfaceTK/catabrowser.py InterfaceTK/cataediteur.py InterfaceTK/centerwindow.py InterfaceTK/change_comm.py InterfaceTK/compobase.py InterfaceTK/compobloc.py InterfaceTK/compocomm.py InterfaceTK/compocommandecomm.py InterfaceTK/compoerror.py InterfaceTK/compofact.py InterfaceTK/compoformule.py InterfaceTK/compojdc.py InterfaceTK/compomacro.py InterfaceTK/compomclist.py InterfaceTK/componiveau.py InterfaceTK/componuplet.py InterfaceTK/compooper.py InterfaceTK/compoparam.py InterfaceTK/compoparameval.py InterfaceTK/compoproc.py InterfaceTK/composimp.py InterfaceTK/definition_cata.py InterfaceTK/eficas.py InterfaceTK/eficas_go.py InterfaceTK/eficas_test.py InterfaceTK/faq.py InterfaceTK/fenetre_mc_inconnus.py InterfaceTK/fonctionpanel.py InterfaceTK/fontes.py InterfaceTK/images.py InterfaceTK/jdcdisplay.py InterfaceTK/listeFichiers.py InterfaceTK/listePatronsTK.py InterfaceTK/macrodisplay.py InterfaceTK/menubar.py InterfaceTK/newsimppanel.py InterfaceTK/options.py InterfaceTK/panels.py InterfaceTK/panelsSalome.py InterfaceTK/patches.py InterfaceTK/plusieursassdpanel.py InterfaceTK/plusieursbasepanel.py InterfaceTK/plusieursintopanel.py InterfaceTK/plusieurspanel.py InterfaceTK/readercata.py InterfaceTK/shellpanel.py InterfaceTK/splash.py InterfaceTK/statusbar.py InterfaceTK/styles.py InterfaceTK/toolbar.py InterfaceTK/tooltip.py InterfaceTK/treeitemincanvas.py InterfaceTK/treewidget.py InterfaceTK/uniqueassdpanel.py InterfaceTK/uniquebasepanel.py InterfaceTK/uniquecomppanel.py InterfaceTK/uniqueintopanel.py InterfaceTK/uniquepanel.py InterfaceTK/uniquesdcopanel.py InterfaceTK/widgets.py Pmw/Alpha_99_9_example/__init__.py Pmw/Alpha_99_9_example/lib/Pmw.def Pmw/Alpha_99_9_example/lib/PmwAlphaExample.py Pmw/Alpha_99_9_example/lib/__init__.py Pmw/Pmw_1_2/__init__.py Pmw/Pmw_1_2/bin/bundlepmw.py Pmw/Pmw_1_2/contrib/DirBrowser.py Pmw/Pmw_1_2/contrib/MCListbox.py Pmw/Pmw_1_2/contrib/PmwFileDialog.py Pmw/Pmw_1_2/contrib/PmwFullTimeCounter.py Pmw/Pmw_1_2/contrib/PmwVerticalGauge.py Pmw/Pmw_1_2/contrib/README Pmw/Pmw_1_2/contrib/TreeBrowser.py Pmw/Pmw_1_2/demos/AboutDialog.py Pmw/Pmw_1_2/demos/All.py Pmw/Pmw_1_2/demos/Args.py Pmw/Pmw_1_2/demos/Balloon.py Pmw/Pmw_1_2/demos/BltGraph.py Pmw/Pmw_1_2/demos/BltTabset.py Pmw/Pmw_1_2/demos/ButtonBox.py Pmw/Pmw_1_2/demos/Colors.py Pmw/Pmw_1_2/demos/ComboBox.py Pmw/Pmw_1_2/demos/ComboBoxDialog.py Pmw/Pmw_1_2/demos/ConfigClass.py Pmw/Pmw_1_2/demos/Counter.py Pmw/Pmw_1_2/demos/CounterDialog.py Pmw/Pmw_1_2/demos/DemoVersion.py Pmw/Pmw_1_2/demos/Dialog.py Pmw/Pmw_1_2/demos/EntryField.py Pmw/Pmw_1_2/demos/ErrorHandling.py Pmw/Pmw_1_2/demos/ExampleDemo.py Pmw/Pmw_1_2/demos/Grid.py Pmw/Pmw_1_2/demos/Group.py Pmw/Pmw_1_2/demos/HistoryText.py Pmw/Pmw_1_2/demos/LabeledWidget.py Pmw/Pmw_1_2/demos/LogicalFont.py Pmw/Pmw_1_2/demos/MainMenuBar.py Pmw/Pmw_1_2/demos/MenuBar.py Pmw/Pmw_1_2/demos/MessageBar.py Pmw/Pmw_1_2/demos/MessageDialog.py Pmw/Pmw_1_2/demos/MessageInfo.py Pmw/Pmw_1_2/demos/MultiLineLabel.py Pmw/Pmw_1_2/demos/NestedDialogs.py Pmw/Pmw_1_2/demos/NoteBook.py Pmw/Pmw_1_2/demos/NoteBook_2.py Pmw/Pmw_1_2/demos/NoteBook_3.py Pmw/Pmw_1_2/demos/OptionMenu.py Pmw/Pmw_1_2/demos/PanedWidget.py Pmw/Pmw_1_2/demos/PanedWidget_2.py Pmw/Pmw_1_2/demos/PromptDialog.py Pmw/Pmw_1_2/demos/RadioSelect.py Pmw/Pmw_1_2/demos/Resources.py Pmw/Pmw_1_2/demos/Resources_Pmw.py Pmw/Pmw_1_2/demos/ScrolledCanvas.py Pmw/Pmw_1_2/demos/ScrolledField.py Pmw/Pmw_1_2/demos/ScrolledFrame.py Pmw/Pmw_1_2/demos/ScrolledListBox.py Pmw/Pmw_1_2/demos/ScrolledText.py Pmw/Pmw_1_2/demos/ScrolledText_2.py Pmw/Pmw_1_2/demos/SelectionDialog.py Pmw/Pmw_1_2/demos/ShowBusy.py Pmw/Pmw_1_2/demos/SpecialCounter.py Pmw/Pmw_1_2/demos/SpecialEntry.py Pmw/Pmw_1_2/demos/Spectrum.py Pmw/Pmw_1_2/demos/SpeedTest.py Pmw/Pmw_1_2/demos/SubClassing.py Pmw/Pmw_1_2/demos/TextDialog.py Pmw/Pmw_1_2/demos/TextDisplay.py Pmw/Pmw_1_2/demos/TimeCounter.py Pmw/Pmw_1_2/demos/WidgetDestroy.py Pmw/Pmw_1_2/doc/AboutDialog.gif Pmw/Pmw_1_2/doc/AboutDialog.html Pmw/Pmw_1_2/doc/Balloon.gif Pmw/Pmw_1_2/doc/Balloon.html Pmw/Pmw_1_2/doc/Blt.html Pmw/Pmw_1_2/doc/ButtonBox.gif Pmw/Pmw_1_2/doc/ButtonBox.html Pmw/Pmw_1_2/doc/Color.html Pmw/Pmw_1_2/doc/ComboBox.gif Pmw/Pmw_1_2/doc/ComboBox.html Pmw/Pmw_1_2/doc/ComboBoxDialog.gif Pmw/Pmw_1_2/doc/ComboBoxDialog.html Pmw/Pmw_1_2/doc/Counter.gif Pmw/Pmw_1_2/doc/Counter.html Pmw/Pmw_1_2/doc/CounterDialog.gif Pmw/Pmw_1_2/doc/CounterDialog.html Pmw/Pmw_1_2/doc/Dialog.gif Pmw/Pmw_1_2/doc/Dialog.html Pmw/Pmw_1_2/doc/EntryField.gif Pmw/Pmw_1_2/doc/EntryField.html Pmw/Pmw_1_2/doc/ExampleDemo.py Pmw/Pmw_1_2/doc/Group.gif Pmw/Pmw_1_2/doc/Group.html Pmw/Pmw_1_2/doc/HistoryText.gif Pmw/Pmw_1_2/doc/HistoryText.html Pmw/Pmw_1_2/doc/LabeledWidget.gif Pmw/Pmw_1_2/doc/LabeledWidget.html Pmw/Pmw_1_2/doc/MainMenuBar.gif Pmw/Pmw_1_2/doc/MainMenuBar.html Pmw/Pmw_1_2/doc/MegaArchetype.html Pmw/Pmw_1_2/doc/MegaToplevel.html Pmw/Pmw_1_2/doc/MegaWidget.html Pmw/Pmw_1_2/doc/MenuBar.gif Pmw/Pmw_1_2/doc/MenuBar.html Pmw/Pmw_1_2/doc/MessageBar.gif Pmw/Pmw_1_2/doc/MessageBar.html Pmw/Pmw_1_2/doc/MessageDialog.gif Pmw/Pmw_1_2/doc/MessageDialog.html Pmw/Pmw_1_2/doc/NoteBook.gif Pmw/Pmw_1_2/doc/NoteBook.html Pmw/Pmw_1_2/doc/OptionMenu.gif Pmw/Pmw_1_2/doc/OptionMenu.html Pmw/Pmw_1_2/doc/PanedWidget.gif Pmw/Pmw_1_2/doc/PanedWidget.html Pmw/Pmw_1_2/doc/PmwFunctions.html Pmw/Pmw_1_2/doc/PromptDialog.gif Pmw/Pmw_1_2/doc/PromptDialog.html Pmw/Pmw_1_2/doc/RadioSelect.gif Pmw/Pmw_1_2/doc/RadioSelect.html Pmw/Pmw_1_2/doc/ScrolledCanvas.gif Pmw/Pmw_1_2/doc/ScrolledCanvas.html Pmw/Pmw_1_2/doc/ScrolledField.gif Pmw/Pmw_1_2/doc/ScrolledField.html Pmw/Pmw_1_2/doc/ScrolledFrame.gif Pmw/Pmw_1_2/doc/ScrolledFrame.html Pmw/Pmw_1_2/doc/ScrolledListBox.gif Pmw/Pmw_1_2/doc/ScrolledListBox.html Pmw/Pmw_1_2/doc/ScrolledText.gif Pmw/Pmw_1_2/doc/ScrolledText.html Pmw/Pmw_1_2/doc/ScrolledText_test.py Pmw/Pmw_1_2/doc/SelectionDialog.gif Pmw/Pmw_1_2/doc/SelectionDialog.html Pmw/Pmw_1_2/doc/TextDialog.gif Pmw/Pmw_1_2/doc/TextDialog.html Pmw/Pmw_1_2/doc/TimeCounter.gif Pmw/Pmw_1_2/doc/TimeCounter.html Pmw/Pmw_1_2/doc/blue_line.gif Pmw/Pmw_1_2/doc/blueball.gif Pmw/Pmw_1_2/doc/bugs.html Pmw/Pmw_1_2/doc/changes.html Pmw/Pmw_1_2/doc/copyright.html Pmw/Pmw_1_2/doc/counter1.gif Pmw/Pmw_1_2/doc/counter2.gif Pmw/Pmw_1_2/doc/demosandtests.html Pmw/Pmw_1_2/doc/dynamicloader.html Pmw/Pmw_1_2/doc/example.py Pmw/Pmw_1_2/doc/example1.gif Pmw/Pmw_1_2/doc/example2.gif Pmw/Pmw_1_2/doc/exercises.py Pmw/Pmw_1_2/doc/features.html Pmw/Pmw_1_2/doc/halfblueball.gif Pmw/Pmw_1_2/doc/howtobuild.html Pmw/Pmw_1_2/doc/howtouse.html Pmw/Pmw_1_2/doc/index.html Pmw/Pmw_1_2/doc/porting.html Pmw/Pmw_1_2/doc/refindex.html Pmw/Pmw_1_2/doc/scale1.gif Pmw/Pmw_1_2/doc/scale2.gif Pmw/Pmw_1_2/doc/starting.html Pmw/Pmw_1_2/doc/todo.html Pmw/Pmw_1_2/doc/transdove.gif Pmw/Pmw_1_2/lib/Pmw.def Pmw/Pmw_1_2/lib/PmwAboutDialog.py Pmw/Pmw_1_2/lib/PmwBalloon.py Pmw/Pmw_1_2/lib/PmwBase.py Pmw/Pmw_1_2/lib/PmwBlt.py Pmw/Pmw_1_2/lib/PmwButtonBox.py Pmw/Pmw_1_2/lib/PmwColor.py Pmw/Pmw_1_2/lib/PmwComboBox.py Pmw/Pmw_1_2/lib/PmwComboBoxDialog.py Pmw/Pmw_1_2/lib/PmwCounter.py Pmw/Pmw_1_2/lib/PmwCounterDialog.py Pmw/Pmw_1_2/lib/PmwDialog.py Pmw/Pmw_1_2/lib/PmwEntryField.py Pmw/Pmw_1_2/lib/PmwGroup.py Pmw/Pmw_1_2/lib/PmwHistoryText.py Pmw/Pmw_1_2/lib/PmwLabeledWidget.py Pmw/Pmw_1_2/lib/PmwLoader.py Pmw/Pmw_1_2/lib/PmwLogicalFont.py Pmw/Pmw_1_2/lib/PmwMainMenuBar.py Pmw/Pmw_1_2/lib/PmwMenuBar.py Pmw/Pmw_1_2/lib/PmwMessageBar.py Pmw/Pmw_1_2/lib/PmwMessageDialog.py Pmw/Pmw_1_2/lib/PmwNoteBook.py Pmw/Pmw_1_2/lib/PmwOptionMenu.py Pmw/Pmw_1_2/lib/PmwPanedWidget.py Pmw/Pmw_1_2/lib/PmwPromptDialog.py Pmw/Pmw_1_2/lib/PmwRadioSelect.py Pmw/Pmw_1_2/lib/PmwScrolledCanvas.py Pmw/Pmw_1_2/lib/PmwScrolledField.py Pmw/Pmw_1_2/lib/PmwScrolledFrame.py Pmw/Pmw_1_2/lib/PmwScrolledListBox.py Pmw/Pmw_1_2/lib/PmwScrolledText.py Pmw/Pmw_1_2/lib/PmwSelectionDialog.py Pmw/Pmw_1_2/lib/PmwTextDialog.py Pmw/Pmw_1_2/lib/PmwTimeCounter.py Pmw/Pmw_1_2/lib/PmwTimeFuncs.py Pmw/Pmw_1_2/lib/__init__.py Pmw/Pmw_1_2/tests/AboutDialog_test.py Pmw/Pmw_1_2/tests/All.py Pmw/Pmw_1_2/tests/Blt_test.py Pmw/Pmw_1_2/tests/ButtonBox_test.py Pmw/Pmw_1_2/tests/Colors_test.py Pmw/Pmw_1_2/tests/ComboBox_test.py Pmw/Pmw_1_2/tests/CounterDialog_test.py Pmw/Pmw_1_2/tests/Counter_test.py Pmw/Pmw_1_2/tests/Dialog_test.py Pmw/Pmw_1_2/tests/EntryField_test.py Pmw/Pmw_1_2/tests/LabeledWidget_test.py Pmw/Pmw_1_2/tests/ManualTests.py Pmw/Pmw_1_2/tests/MegaWidget_test.py Pmw/Pmw_1_2/tests/MessageDialog_test.py Pmw/Pmw_1_2/tests/NoteBook_test.py Pmw/Pmw_1_2/tests/OptionMenu_test.py Pmw/Pmw_1_2/tests/Options_test.py Pmw/Pmw_1_2/tests/PanedWidget_test.py Pmw/Pmw_1_2/tests/PmwBase_test.py Pmw/Pmw_1_2/tests/PromptDialog_test.py Pmw/Pmw_1_2/tests/RadioSelect_test.py Pmw/Pmw_1_2/tests/ScrolledCanvas_test.py Pmw/Pmw_1_2/tests/ScrolledField_test.py Pmw/Pmw_1_2/tests/ScrolledFrame_test.py Pmw/Pmw_1_2/tests/ScrolledListBox_test.py Pmw/Pmw_1_2/tests/ScrolledText_test.py Pmw/Pmw_1_2/tests/SelectionDialog_test.py Pmw/Pmw_1_2/tests/Test.py Pmw/Pmw_1_2/tests/TestVersion.py Pmw/Pmw_1_2/tests/TextDialog_test.py Pmw/Pmw_1_2/tests/Tkinter_test.py Pmw/Pmw_1_2/tests/earthris.gif Pmw/Pmw_1_2/tests/flagup.bmp Pmw/README Pmw/__init__.py Ui/OptionsEditeur.py Ui/OptionsEditeur.ui Ui/OptionsPdf.py Ui/OptionsPdf.ui Ui/aideQT.py Ui/aideQT.ui Ui/desChoixCata.py Ui/desChoixCata.ui Ui/desCommande.py Ui/desCommande.ui Ui/desCommentaire.py Ui/desCommentaire.ui Ui/desError.py Ui/desError.ui Ui/desFormule.py Ui/desFormule.ui Ui/desInactif.py Ui/desInactif.ui Ui/desInclude.py Ui/desInclude.ui Ui/desListeParam.py Ui/desListeParam.ui Ui/desMCFact.py Ui/desMCFact.ui Ui/desMCListAjout.py Ui/desMCListAjout.ui Ui/desMacro.py Ui/desMacro.ui Ui/desParam.py Ui/desParam.ui Ui/desPlusieursBase.py Ui/desPlusieursBase.ui Ui/desPlusieursInto.py Ui/desPlusieursInto.ui Ui/desPoursuite.py Ui/desPoursuite.ui Ui/desRacine.py Ui/desRacine.ui Ui/desSelectVal.py Ui/desSelectVal.ui Ui/desUniqueASSD.py Ui/desUniqueASSD.ui Ui/desUniqueBase.py Ui/desUniqueBase.ui Ui/desUniqueComp.py Ui/desUniqueComp.ui Ui/desUniqueInto.py Ui/desUniqueInto.ui Ui/desUniqueSDCO.py Ui/desUniqueSDCO.ui Ui/desUniqueSDCOInto.py Ui/desUniqueSDCOInto.ui Ui/desVisu.py Ui/desVisu.ui Ui/image120.gif Ui/image120.png Ui/image240.gif Ui/makefile Ui/myMain.py Ui/myMain.ui --- diff --git a/Aster/Cata/cataSTA9/Intranet/__init__.py b/Aster/Cata/cataSTA9/Intranet/__init__.py deleted file mode 100644 index 88770065..00000000 --- a/Aster/Cata/cataSTA9/Intranet/__init__.py +++ /dev/null @@ -1,19 +0,0 @@ -#@ MODIF __init__ Intranet DATE 18/09/2007 AUTEUR DURAND C.DURAND - -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2007 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# ====================================================================== diff --git a/Aster/Cata/cataSTA9/Intranet/calc_eolienne.py b/Aster/Cata/cataSTA9/Intranet/calc_eolienne.py deleted file mode 100644 index e565b6cb..00000000 --- a/Aster/Cata/cataSTA9/Intranet/calc_eolienne.py +++ /dev/null @@ -1,1722 +0,0 @@ -#@ MODIF calc_eolienne Intranet DATE 18/09/2007 AUTEUR DURAND C.DURAND - -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2007 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# ====================================================================== -# -# LISTE DES FONCTIONS, MACROS et CATALOGUES -# -# MACROS -# -# calc_char_houle -# macr_calc_eolienne -# -# FONCTIONS -# -# mail_eolienne -# eolien_regression -# lect_resu_stream -# donn_boucle_pas_temps -# extr_char_houle -# -# CATALOGUES -# -# CALC_CHAR_HOULE -# MACR_CALC_EOLIENNE -# -#____________________________________________________________________ -# -# On charge les modules necessaires -import os -import Numeric -import re -import math -# -# permet de definir dans le meme fichier les catalogues et les macros -from Cata.cata import * -# -#____________________________________________________________________ -#____________________________________________________________________ -# -#____________________________________________________________________ -#___________________ DEBUT MACRO calc_char_houle ____________________ -# -# -def calc_char_houle_ops(self, INFO, STREAM, IMPRESSION, **args): -# -# 1. args est le dictionnaire des arguments -# args.keys() est la liste des mots-clés -# args.keys()[0] est la premiere valeur de cette liste -# args.keys()[1:] est la liste des valeurs suivantes dans cette liste -# args.keys(mot_cle) représente le contenu de la variable mot_cle dans la macro appelante. - - """ Calcule le chargement du a la houle. """ - -# On charge les modules nécessaires - from Accas import _F - import aster - -#____________________________________________________________________ -# -# 1. Préalables -#____________________________________________________________________ - -# 1.1 ==> La macro compte pour 1 dans l'exécution des commandes - - self.set_icmd(1) - -# 1.2 ==> On importe les définitions des commandes Aster utilisées -# dans la macro - - EXEC_LOGICIEL = self.get_cmd("EXEC_LOGICIEL") - IMPR_TABLE= self.get_cmd("IMPR_TABLE") - DEFI_FICHIER= self.get_cmd("DEFI_FICHIER") - -# 1.3 ==> Le nom des programmes à lancer - -# repertoire_outils = "/home/eolien/ASTER_EOLIEN/" - repertoire_outils = aster.repout() - calc_houle = repertoire_outils + "calc_houle" - -# 1.4 ==> Initialisations - - erreur = 0 - erreur_partiel = [0] - Rep_Calc_ASTER = os.getcwd() - - messages_erreur = { 0 : " Tout va bien.", - 1 : " Impossible de créer le répertoire de travail pour le logiciel de calcul de houle.", - 100 : " Erreur." } - - while not erreur : - -#____________________________________________________________________ -# -# 2. Répertoires et fichiers -#____________________________________________________________________ -# - -# 2.1. ==> Création du répertoire pour l'exécution du logiciel STREAM_FM - - Nom_Rep_local_houle = "tmp_stream" - Rep_Calc_LOGICIEL_local_houle = os.path.join(".",Nom_Rep_local_houle) - Rep_Calc_LOGICIEL_global_houle = os.path.join(Rep_Calc_ASTER,Nom_Rep_local_houle) - - try : - os.mkdir(Rep_Calc_LOGICIEL_global_houle) - except os.error,erreur_partiel : - self.cr.warn("Code d'erreur de mkdir : " + str(erreur_partiel[0]) + " : " + erreur_partiel[1]) - self.cr.fatal("Impossible de créer le répertoire de travail pour le logiciel de calcul de houle : "+Rep_Calc_LOGICIEL_global_houle) - erreur = 1 - break - -# 2.2. ==> On cree un fichier annexe pour transmettre des infos à la procédure de lancement -# de STREAM_FM - - fic_Info_ASTER = os.path.join(Rep_Calc_LOGICIEL_global_houle,"InfoExecASTER") - f_execAster = open(fic_Info_ASTER, "w") - f_execAster.write(str(INFO)+"\n") - f_execAster.close() - -#____________________________________________________________________ -# -# 3. Décodage des arguments de la macro-commande -# et création des fichiers pour STREAM_FM -#____________________________________________________________________ - -# 3.1. ==> Les fichiers pour le logiciel STREAM_FM -# Ils sont créés dans le répertoire d'exécution du logiciel, avec leurs noms officiels - - fic_data_HT = os.path.join(Rep_Calc_LOGICIEL_global_houle,"AMA_HT.par") - fic_data_FM = os.path.join(Rep_Calc_LOGICIEL_global_houle,"AMA_FM.par") - -# 3.2 ==> Construction du fichier 'data_HT' - -# 3.2.1 ==> Ouverture du fichier data_HT dans un répertoire temporaire - - f_menu = open(fic_data_HT, "w") - -# 3.2.2 ==> Lecture et écriture des données nécessaires - - prof = STREAM['PROFONDEUR'] - h_houle = STREAM['H_HOULE'] - peri_houle = STREAM['PERI_HOULE'] - courant_euler = STREAM['COUR_EULERIEN'] - ordre_fonc = STREAM['ORDR_FONC_COURAN'] - - f_menu.write(str(prof)+" <= Profondeur d'eau (m)\n") - f_menu.write(str(h_houle)+" <= Hauteur de houle (crete-a-creux) (m)\n") - f_menu.write(str(peri_houle)+" <= Periode de houle (s)\n") - f_menu.write(str(courant_euler)+" <= Vitesse du courant eulerien (m/s)\n") - f_menu.write(str(ordre_fonc)+" <= ordre de la fonction de courant (m/s)\n") - -# 3.2.3 ==> Fermeture du fichier data_HT - - f_menu.close() - - if INFO >= 2 : - print "===========================\n" - print "Contenu du fichier data_HT :" - fichier = open (fic_data_HT,"r") - les_lignes = fichier.readlines() - fichier.close() - for ligne in les_lignes : - print ligne[:-1] - print "===========================\n" - -# 3.3 ==> Construction du fichier "data_FM" - -# 3.3.1 ==> Ouverture du fichier - - f_FM = open(fic_data_FM, "w") - -# 3.3.2 ==> Lecture et écriture des données nécessaires - - diam = STREAM['DEXT_HAUT_BASE'] - coef_trainee = STREAM['COEF_TRAINEE'] - coef_inertie = STREAM['COEF_INERTIE'] - nb_nive_z = STREAM['NB_POINTS_VERT'] - nb_dt_par_t = STREAM['NB_INTER_PERI'] - - f_FM.write(str(diam)+" <= Diametre du cylindre (m)\n") - f_FM.write(str(coef_trainee)+" <= Coefficient de trainee Cd\n") - f_FM.write(str(coef_inertie)+" <= Coefficient d'inertie Cm\n") - f_FM.write(str(nb_nive_z)+" <= Nbe de points sur la verticale\n") - f_FM.write(str(nb_dt_par_t)+" <= Nbe de pas de temps sur une periode de houle\n") - -# 3.3.3 ==> Fermeture du fichier data_FM - - f_FM.close() - - if INFO >= 2 : - print "===========================\n" - print "Contenu du fichier data_FM :" - fichier = open (fic_data_FM,"r") - les_lignes = fichier.readlines() - fichier.close() - for ligne in les_lignes : - print ligne[:-1] - print "===========================\n" - -# 3.4 ==> Nom du fichier qui contiendra le résultat - - if (IMPRESSION['UNITE'] != None) : - Unit_Fich_Resu = 'fort.'+str(IMPRESSION['UNITE']) - -#____________________________________________________________________ -# -# 4. Ecriture de la commande d"exécution du logiciel STREAM -# -# Remarque : dans la donnée de la version du logiciel STREAM, il faut remplacer -# le _ de la donnée par un ., qui -# est interdit dans la syntaxe du langage de commandes ASTER -# Remarque : il faut remplacer le N majuscule de la donnee par -# un n minuscule, qui est interdit dans la syntaxe du langage -# de commandes ASTER -#____________________________________________________________________ -# - - VERSION="aster" - LOGICIEL = "STREAM" - - EXEC_LOGICIEL ( ARGUMENT = (Rep_Calc_LOGICIEL_global_houle, # nom du repertoire du calcul de houle - LOGICIEL, # nom du logiciel de calcul de houle - VERSION, # version du logiciel de calcul de houle - ), - LOGICIEL = calc_houle - ) - -#____________________________________________________________________ -# -# 5. Lecture du fichier de résultats STREAM_FM -#____________________________________________________________________ -# -# 5.1 ==> Ouverture, lecture et fermeture du fichier "AMA_FM.res" - - if (IMPRESSION['UNITE'] != None) : - fic_resuStream = os.path.join(Rep_Calc_LOGICIEL_global_houle,"AMA_FM.res") - f_resu = open(fic_resuStream, "r") - lignes = f_resu.readlines() - f_resu.close() - - Fic_Tabl_Resu = os.path.join(Rep_Calc_ASTER,Unit_Fich_Resu) - f_resu = open(Fic_Tabl_Resu, "w") - f_resu.writelines(lignes) - f_resu.close() -# -#____________________________________________________________________ -# -# 6. C'est fini ! -#____________________________________________________________________ -# - break - -# 6.1. ==> Arret en cas d'erreur - - if erreur : - if not messages_erreur.has_key(erreur) : - erreur = 100 - self.cr.fatal(messages_erreur[erreur]) - - return - -#____________________________________________________________________ -#____________________ FIN MACRO calc_char_houle _____________________ -# -#____________________________________________________________________ -#___________________ DEBUT FONCTION mail_eolienne ___________________ -# -# -# ===> Creation des fichiers de commandes GIBI -#____________________________________________________________________ -# - -def mail_eolienne(H_TOTALE, H_BASE, H_IMMERGEE, H_MOYEU, H_JONCTION, DECAL_PALES, - DEXT_NACELLE, EPAIS_NACELLE, DEXT_HAUT_BASE, DEXT_BAS_BASE, - EPAIS_HAUT_BASE, EPAIS_BAS_BASE, DEXT_HAUT_FUT, DEXT_BAS_FUT, - EPAIS_HAUT_FUT, EPAIS_BAS_FUT, NB_ELEM_BASE, NB_ELEM_FUT, - NBEL_EPAIS_BASE, NBEL_EPAIS_FUT, NBEL_DCIR_BASE, NBEL_DCIR_FUT, - ANGLE_VENT_AXE_X, - MODELISATION, TYPE_ELEM, NIVE_GIBI, fichier_datg) : - -# -# 1 ==> Reccuperation du repertoire dans lequel s'execute le calcul ASTER -# - Rep_Calc_ASTER = os.getcwd() - -# -# 2 ==> Decoupage des mailles de la base en fonction du niveau d'eau -# - lb = H_BASE / NB_ELEM_BASE - nbi = int(H_IMMERGEE/lb) - hbe = H_BASE - H_IMMERGEE - - # CAS 1 - if ( ((H_IMMERGEE/lb)-nbi) < 0.5 ) : - lbi = H_IMMERGEE/nbi - if (hbe > 0.0) : - nbe = NB_ELEM_BASE - nbi - lbe = hbe/nbe - else : - nbe = 0 - # CAS 2 - if ( ((H_IMMERGEE/lb)-nbi) >= 0.5 ) : - lbi = H_IMMERGEE/(nbi+1) - nbe = NB_ELEM_BASE - (nbi+1) - lbe = hbe/nbe - nbi = nbi + 1 - -# -# 3 ==> Ecriture des donnees necessaires dans le fichier auxiliaire -# - if MODELISATION == 'POUTRE' : - - # 3.1 ==> Ouverture du fichier auxiliaire - - fichier_auxi = os.path.join(Rep_Calc_ASTER,"fichaux") - fdaux = open (fichier_auxi,'w') - - # 3.2 ==> Ecriture des donnees dans le fichier auxiliaire - - j = 0 - - for i in range(nbi) : - j = j+1 - fdaux.write("base"+str(j)+" = baset . "+str(j)+";\n") - if hbe > 0.0 : - for i in range(nbe) : - j = j+1 - fdaux.write("base"+str(j)+" = baset . "+str(j)+";\n") - - for i in range(NB_ELEM_FUT) : - fdaux.write("fut"+str(i+1)+" = futt . "+str(i+1)+";\n") - - fdaux.write("SAUV FORM eolienne;\n") - fdaux.write("FIN;\n") - - # 3.3 ==> Fermeture du fichier auxiliaire - - fdaux.close() - -# -# 4 ==> Ecriture des donnees necessaires dans le fichier de donnees GIBI -# - -# 4.1 ==> Ouverture du fichier de données GIBI - - fdgib = open (fichier_datg,'w') - - -# 4.2 ==> Ecriture des donnees dans le fichier de donnees GIBI - - fdgib.write("*********************************\n") - fdgib.write("** Maillage d'une eolienne en mer\n") - fdgib.write("*********************************\n") - fdgib.write("***********************\n") - fdgib.write("***********************\n") - fdgib.write("** donnees geometriques\n") - fdgib.write("***********************\n") - - fdgib.write("opti nive "+str(NIVE_GIBI)+";\n") - - if MODELISATION == 'POUTRE' : - fdgib.write("modbase = 'poutre';\n") - fdgib.write("modfut = 'poutre';\n") - if MODELISATION == 'COQUE' : - fdgib.write("modbase = 'coque';\n") - fdgib.write("modfut = 'coque';\n") - if MODELISATION == '3D' : - fdgib.write("modbase = '3D';\n") - fdgib.write("modfut = '3D';\n") - if TYPE_ELEM == 'CUB8' : fdgib.write("quad = 'non';\n") - if TYPE_ELEM == 'CU20' : fdgib.write("quad = 'oui';\n") - - fdgib.write("**** hauteur totale du monopode (hors nacelle)\n") - fdgib.write("h_totale = "+str(H_TOTALE)+";\n") - fdgib.write("**** hauteur de la base du monopode\n") - fdgib.write("hb = "+str(H_BASE)+";\n") - fdgib.write("**** hauteur immergee (deduite du calcul par STREAM)\n") - fdgib.write("hbi = "+str(H_IMMERGEE)+";\n") - fdgib.write("**** nombre de mailles immergees de la base\n") - fdgib.write("nbi = "+str(nbi)+";\n") - fdgib.write("**** hauteur emergee\n") - fdgib.write("hbe = "+str(hbe)+";\n") - fdgib.write("**** nombre de mailles emergees de la base\n") - fdgib.write("nbe = "+str(nbe)+";\n") - fdgib.write("**** decoupage vertical\n") - fdgib.write("nb_base = "+str(NB_ELEM_BASE)+";\n") - fdgib.write("nb_fut = "+str(NB_ELEM_FUT)+";\n") - fdgib.write("**** diametre et epaisseur bas du fut\n") - fdgib.write("dex_bfut = "+str(DEXT_BAS_FUT)+";\n") - fdgib.write("ep_bfut = "+str(EPAIS_BAS_FUT)+";\n") - fdgib.write("**** diametre et epaisseur haut du fut\n") - fdgib.write("dex_hfut = "+str(DEXT_HAUT_FUT)+";\n") - fdgib.write("ep_hfut = "+str(EPAIS_HAUT_FUT)+";\n") - fdgib.write("**** diametre et epaisseur bas de la base\n") - fdgib.write("dex_bbas = "+str(DEXT_BAS_BASE)+";\n") - fdgib.write("ep_bbas = "+str(EPAIS_BAS_BASE)+";\n") - fdgib.write("**** diametre et epaisseur haut de la base\n") - fdgib.write("dex_hbas = "+str(DEXT_HAUT_BASE)+";\n") - fdgib.write("ep_hbas = "+str(EPAIS_HAUT_BASE)+";\n") - - if MODELISATION == '3D' or MODELISATION == 'COQUE' : - fdgib.write("**** nombre d'elements sur un demi-cercle\n") - fdgib.write("nbcirfut = "+str(NBEL_DCIR_FUT)+";\n") - fdgib.write("nbcirbas = "+str(NBEL_DCIR_BASE)+";\n") - fdgib.write("**** hauteur de la jonction base/fut\n") - fdgib.write("hbj = "+str(H_JONCTION)+";\n") - if MODELISATION == '3D' : - fdgib.write("**** nombre d'elements dans l'epaisseur\n") - fdgib.write("nbep_fut = "+str(NBEL_EPAIS_FUT)+";\n") - fdgib.write("nbep_bas = "+str(NBEL_EPAIS_BASE)+";\n") - - fdgib.write("**** angle entre la pression du vent et l'axe X (degres)\n") - fdgib.write("alpha = "+str(ANGLE_VENT_AXE_X)+";\n") - fdgib.write("**** decalage pales\n") - fdgib.write("dec0 = "+str(DECAL_PALES)+";\n") - fdgib.write("**** hauteur moyeu\n") - fdgib.write("hp0 = "+str(H_MOYEU)+";\n") - - fdgib.write("opti echo 0;\n") -# loc_datg = "/home/eolien/DATG/" - loc_datg = aster.repdex() - fdgib.write("* \n") - fdgib.write(open(os.path.join(loc_datg, 'calc_eolienne.datg'), 'r').read()) - -# 4.3 ==> Fermeture du fichier de donnees GIBI - - fdgib.close() - -# 5 ==> FIN - - return - -#____________________________________________________________________ -#____________________ FIN FONCTION mail_eolienne ____________________ -# -#____________________________________________________________________ -# -#____________________________________________________________________ -#_________________ DEBUT FONCTION eolien_regression _________________ -# -# -# ===> Regression selon les moindres carres -#____________________________________________________________________ -# -# -def eolien_regression (liste, INFO,) : -# -# -#____________________________________________________________________ -# -# MOINDRES CARRES -#____________________________________________________________________ -# -# Calcul des coefficients teta0, teta1, teta2 et teta3 de -# l'application qui passe au mieux (au sens des moindres carres) -# par les couples (profondeur,force lineique). - - -# 1 ==> Initialisation - - -# 2 ==> Nombre de points calcules par STREAM selon l'axe vertical - - dim = liste.shape[0] - -# Controle : dim == Nb_valeur a voir - -# 3 ==> Definition des polynomes - - global P0, P1, P2, P3 - - def P0(): - return 1 - - def P1(alpha1, x): - return (x-alpha1) - - def P2(alpha1, alpha2, beta2, x): - return (x-alpha2)*(x-alpha1) - beta2 - - def P3(alpha1, alpha2, alpha3, beta2, beta3, x): - return (x-alpha3)*((x-alpha2)*(x-alpha1) - beta2) - beta3*(x-alpha1) - -# 4 ==> Definition de la fonction polynomiale de degre 3 - - def FF3(alpha1, alpha2, alpha3, beta2, beta3, teta0, teta1, teta2, teta3, x): - return teta0*P0() + teta1*P1(alpha1,x) + teta2*P2(alpha1,alpha2,beta2,x) + teta3*P3(alpha1,alpha2,alpha3,beta2,beta3,x) - -# 5 ==> Calcul des coefficients alpha1, alpha2, alpha3, beta2 et beta3 - - numerateur_alpha1 = 0 - denominateur_alpha1 = 0 - alpha1 = 0 - for i in range(dim) : - numerateur_alpha1 = numerateur_alpha1 + liste[[i,0]]*P0()**2 - denominateur_alpha1 = denominateur_alpha1 + P0()**2 - - alpha1 = numerateur_alpha1/denominateur_alpha1 - - numerateur_alpha2 = 0 - denominateur_alpha2 = 0 - alpha2 = 0 - numerateur_beta2 = 0 - denominateur_beta2 = 0 - beta2 = 0 - for i in range(dim) : - numerateur_alpha2 = numerateur_alpha2 + liste[[i,0]]*P1(alpha1,liste[[i,0]])**2 - denominateur_alpha2 = denominateur_alpha2 + P1(alpha1,liste[[i,0]])**2 - numerateur_beta2 = numerateur_beta2 + P1(alpha1,liste[[i,0]])**2 - denominateur_beta2 = denominateur_beta2 + P0()**2 - - alpha2 = numerateur_alpha2/denominateur_alpha2 - beta2 = numerateur_beta2/denominateur_beta2 - - numerateur_alpha3 = 0 - denominateur_alpha3 = 0 - alpha3 = 0 - numerateur_beta3 = 0 - denominateur_beta3 = 0 - beta3 = 0 - for i in range(dim) : - numerateur_alpha3 = numerateur_alpha3 + liste[[i,0]]*P2(alpha1,alpha2,beta2,liste[[i,0]])**2 - denominateur_alpha3 = denominateur_alpha3 + P2(alpha1,alpha2,beta2,liste[[i,0]])**2 - numerateur_beta3 = numerateur_beta3 + P2(alpha1,alpha2,beta2,liste[[i,0]])**2 - denominateur_beta3 = denominateur_beta3 + P1(alpha1,liste[[i,0]])**2 - - alpha3 = numerateur_alpha3/denominateur_alpha3 - beta3 = numerateur_beta3/denominateur_beta3 - -# 6 ==> Calcul des estimateurs cherches : teta0, teta1, teta2, teta3 - - numerateur_teta0 = 0 - denominateur_teta0 = 0 - teta0 = 0 - for i in range(dim) : - numerateur_teta0 = numerateur_teta0 + liste[[i,1]]*P0() - denominateur_teta0 = denominateur_teta0 + P0()**2 - - teta0 = numerateur_teta0/denominateur_teta0 - - numerateur_teta1 = 0 - denominateur_teta1 = 0 - teta1 = 0 - for i in range(dim) : - numerateur_teta1 = numerateur_teta1 + liste[[i,1]]*P1(alpha1,liste[[i,0]]) - denominateur_teta1 = denominateur_teta1 + P1(alpha1,liste[[i,0]])**2 - - teta1 = numerateur_teta1/denominateur_teta1 - - numerateur_teta2 = 0 - denominateur_teta2 = 0 - teta2 = 0 - for i in range(dim) : - numerateur_teta2 = numerateur_teta2 + liste[[i,1]]*P2(alpha1,alpha2,beta2,liste[[i,0]]) - denominateur_teta2 = denominateur_teta2 + P2(alpha1,alpha2,beta2,liste[[i,0]])**2 - - teta2 = numerateur_teta2/denominateur_teta2 - - numerateur_teta3 = 0 - denominateur_teta3 = 0 - teta3 = 0 - for i in range(dim) : - numerateur_teta3 = numerateur_teta3 + liste[[i,1]]*P3(alpha1,alpha2,alpha3,beta2,beta3,liste[[i,0]]) - denominateur_teta3 = denominateur_teta3 + P3(alpha1,alpha2,alpha3,beta2,beta3,liste[[i,0]])**2 - - teta3 = numerateur_teta3/denominateur_teta3 - -# 7 ==> Impression de certains resultats si INFO == 2 - - if (INFO == 2) : - print " " - print " RESULTATS " - print " " - print " teta0 = ", teta0 - print " teta1 = ", teta1 - print " teta2 = ", teta2 - print " teta3 = ", teta3 - print " " - - print " ===> VERIFICATION INTERPOLATION\n" - print " No point - profondeur - valeur STREAM - valeur par moindres carres \n" - for i in range(dim) : - print ' %3d %12.4f %12.4f %12.4f' % (i+1,liste[[i,0]],liste[[i,1]],FF3(alpha1, alpha2, alpha3, beta2, beta3, teta0, teta1, teta2, teta3,liste[[i,0]])) - - return (teta0,teta1,teta2,teta3,alpha1,alpha2,alpha3,beta2,beta3) - -#____________________________________________________________________ -#_________________ FIN FONCTION eolien_regression ___________________ -# -#____________________________________________________________________ -# -#____________________________________________________________________ -#_________________ DEBUT FONCTION lect_resu_stream __________________ -# -# -# ===> Lecture du fichier de resultats STREAM_FM -#____________________________________________________________________ -# - -def lect_resu_stream(INFO) : - -# 1 ==> Ouverture, lecture et fermeture du fichier "AMA_FM.res" - - Rep_Calc_ASTER = os.getcwd() - Nom_Rep_local_houle = "tmp_stream" - Rep_Calc_LOGICIEL_local_houle = os.path.join(".",Nom_Rep_local_houle) - Rep_Calc_LOGICIEL_global_houle = os.path.join(Rep_Calc_ASTER,Nom_Rep_local_houle) - - fic_resuStream = os.path.join(Rep_Calc_LOGICIEL_global_houle,"AMA_FM.res") - f_resu = open(fic_resuStream, "r") - lignes = f_resu.readlines() - f_resu.close() - -# 2 ==> Lecture du nombre de points (valeurs de forces lineiques). -# Lecture du nombre par lequel la periode a ete decoupee -# ATENTION ==> le nombre de pas de temps est egal a ce nombre plus un. - - compt_temps = 0 - compt_valeur = 0 - dict_temps = {} - - for i in range(len(lignes)) : - ligne = lignes[i].split() - print" ligne = ",ligne - if ligne[0] == "/PERIODE" and ligne[2] == "HOULE.................T........:" : - periode_houle = float(ligne[len(ligne)-2]) - - if INFO == 2 : - print " Periode de houle = ",periode_houle - - if ligne[0] == "/NB" and ligne[2] == "POINTS" : - Nb_valeur = int(ligne[len(ligne)-1]) - - if INFO == 2 : - print " Nb_valeur = ",Nb_valeur - - if ligne[0] == "/NB" and ligne[4] == "TEMPS" : - Nb_pas_temps = int(ligne[len(ligne)-1]) - - if INFO == 2 : - print " Nb_pas_temps = ",Nb_pas_temps - break - - return(periode_houle,Nb_valeur,Nb_pas_temps,lignes) - -#____________________________________________________________________ -#__________________ FIN FONCTION lect_resu_stream ___________________ -# -#____________________________________________________________________ -# -#____________________________________________________________________ -#_______________ DEBUT FONCTION donn_boucle_pas_temps _______________ -# -# -# ===> Preparation donnees necessaires a la boucle sur les pas de temps -# et verification du nombre de pas de temps -#____________________________________________________________________ -# - -def donn_boucle_pas_temps(lignes,Nb_pas_temps) : - -# 1 ==> Construction du dictionnaire contenant : -# pas_de_temps : numeros de ligne du fichier resu_STREAM_FM - - compt_temps = 0 - dict_temps = {} - - for i in range(len(lignes)) : - ligne = lignes[i].split() - if len(ligne) != 0 : - if ligne[0] == "#TITRE" and ligne[1] == "TEMPS" : - compt_temps = compt_temps + 1 - dict_temps["TEMPS_"+str(compt_temps)] = i+1 - -# 2 ==> Controle de l'egalite : compt_temps == Nb_pas_temps+1 -# et arret en cas d'erreur. - - if compt_temps != (Nb_pas_temps+1) : - print"\n IL Y A UN PROBLEME DANS DE NOMBRE DE PAS DE TEMPS.\n" - - return(dict_temps) -# -#____________________________________________________________________ -#________________ FIN FONCTION donn_boucle_pas_temps ________________ -# -#____________________________________________________________________ -# -#____________________________________________________________________ -#__________________ DEBUT FONCTION extr_char_houle __________________ -# -# -# ===> Extraction des couples (profondeur,force lineique) -# du fichier resu_STREAM_FM au pas de temps courant et -# remplissage de la liste de travail. -#____________________________________________________________________ -# -##################### -# VALEUR TEST -# -test = 'NON' -# Nb_pas_temps = 0 -##################### - -def extr_char_houle(k,dict_temps,Nb_valeur,lignes) : - - liste = Numeric.zeros((Nb_valeur,2), Numeric.Float) - - nume_ligne_temps = dict_temps["TEMPS_"+str(k)] - range_depart = int(nume_ligne_temps) + 2 - range_arrive = int(nume_ligne_temps) + Nb_valeur + 3 - for l in range(range_depart, range_arrive) : - ligne = lignes[l].split() - if (len(ligne) != 0) : - Flag_Val=re.match(r'^[-]?([0-9]+\.?[0-9]*|\.[0-9]+)([eE][+-]?[0-9]+)?$',ligne[0]) - if (Flag_Val != None) : - liste[[(l-range_depart),0]] = float(ligne[0]) - liste[[(l-range_depart),1]] = float(ligne[1]) - - return(range_depart,range_arrive,liste) - -#____________________________________________________________________ -#___________________ FIN FONCTION extr_char_houle ___________________ -# -# _____________________________ -# _______________ -# _____________________________ -# -#____________________________________________________________________ -#__________________ DEBUT MACRO macr_calc_eolienne __________________ -# -# -# ===> MACRO COMMANDE MACR_CALC_EOLIENNE -# -#____________________________________________________________________ -# -# SCRIPT PYTHON -# -def macr_calc_eolienne_ops(self, INFO, MONOPODE, EXEC_MAILLAGE, AFFE_MATERIAU, CHARGEMENT, - IMPRESSION, MODELISATION, NOM_MAIL_REF, TYPE_ELEM, FATIGUE, **args) : - - """ Calcule la structure de l'eolienne en mer. """ - -# On charge les modules nécessaires - from Accas import _F - import aster -# import os - -#____________________________________________________________________ -# -# 1. Préalables -#____________________________________________________________________ -# -# 1.1 ==> La macro compte pour 1 dans l'exécution des commandes - - self.set_icmd(1) - erreur = 0 - -# 1.2 ==> On importe les définitions des commandes Aster utilisées -# dans la macro - - affemateriau = AFFE_MATERIAU -# impression = IMPRESSION - PRE_GIBI = self.get_cmd("PRE_GIBI") - EXEC_LOGICIEL = self.get_cmd("EXEC_LOGICIEL") - LIRE_MAILLAGE = self.get_cmd("LIRE_MAILLAGE") - DEFI_GROUP = self.get_cmd("DEFI_GROUP") - CREA_MAILLAGE = self.get_cmd("CREA_MAILLAGE") - MODI_MAILLAGE = self.get_cmd("MODI_MAILLAGE") - AFFE_CARA_ELEM = self.get_cmd("AFFE_CARA_ELEM") - AFFE_MODELE = self.get_cmd("AFFE_MODELE") - AFFE_MATERIAU = self.get_cmd("AFFE_MATERIAU") - FORMULE = self.get_cmd("FORMULE") - AFFE_CHAR_MECA_F= self.get_cmd("AFFE_CHAR_MECA_F") - AFFE_CHAR_MECA= self.get_cmd("AFFE_CHAR_MECA") - DEFI_LIST_REEL= self.get_cmd("DEFI_LIST_REEL") - STAT_NON_LINE= self.get_cmd("STAT_NON_LINE") - MECA_STATIQUE= self.get_cmd("MECA_STATIQUE") - CREA_CHAMP= self.get_cmd("CREA_CHAMP") - PROJ_CHAMP= self.get_cmd("PROJ_CHAMP") - CREA_RESU= self.get_cmd("CREA_RESU") - CALC_ELEM= self.get_cmd("CALC_ELEM") -# -# IMPR_CO= self.get_cmd("IMPR_CO") -# - IMPR_RESU= self.get_cmd("IMPR_RESU") - CALC_NO= self.get_cmd("CALC_NO") - CALC_FATIGUE= self.get_cmd("CALC_FATIGUE") - DETRUIRE= self.get_cmd("DETRUIRE") - DEFI_FICHIER= self.get_cmd("DEFI_FICHIER") - -# 1.3 ==> Lecture des donnees - - H_TOTALE = MONOPODE['H_TOTALE'] - H_BASE = MONOPODE['H_BASE'] - H_MOYEU = MONOPODE['H_MOYEU'] - DECAL_PALES = MONOPODE['DECAL_PALES'] - DEXT_HAUT_BASE = MONOPODE['DEXT_HAUT_BASE'] - DEXT_BAS_BASE = MONOPODE['DEXT_BAS_BASE'] - EPAIS_HAUT_BASE = MONOPODE['EPAIS_HAUT_BASE'] - EPAIS_BAS_BASE = MONOPODE['EPAIS_BAS_BASE'] - DEXT_HAUT_FUT = MONOPODE['DEXT_HAUT_FUT'] - DEXT_BAS_FUT = MONOPODE['DEXT_BAS_FUT'] - EPAIS_HAUT_FUT = MONOPODE['EPAIS_HAUT_FUT'] - EPAIS_BAS_FUT = MONOPODE['EPAIS_BAS_FUT'] - NB_ELEM_BASE = MONOPODE['NB_ELEM_BASE'] - NB_ELEM_FUT = MONOPODE['NB_ELEM_FUT'] - if (MODELISATION == '3D' or MODELISATION == 'COQUE') : - H_JONCTION = MONOPODE['H_JONCTION'] - DEXT_NACELLE = MONOPODE['DEXT_NACELLE'] - EPAIS_NACELLE = MONOPODE['EPAIS_NACELLE'] - NBEL_EPAIS_BASE = MONOPODE['NBEL_EPAIS_BASE'] - NBEL_EPAIS_FUT = MONOPODE['NBEL_EPAIS_FUT'] - else : - H_JONCTION = None - DEXT_NACELLE = None - EPAIS_NACELLE = None - NBEL_EPAIS_BASE = None - NBEL_EPAIS_FUT = None - - if (MODELISATION == '3D') : - NBEL_DCIR_BASE = MONOPODE['NBEL_DCIR_BASE'] - NBEL_DCIR_FUT = MONOPODE['NBEL_DCIR_FUT'] - else : - NBEL_DCIR_BASE = None - NBEL_DCIR_FUT = None - - ANGLE_VENT_AXE_X = CHARGEMENT['ANGLE_VENT_AXE_X'] - - LOGICIEL = EXEC_MAILLAGE['LOGICIEL'] - UNITE_DATG = EXEC_MAILLAGE['UNITE_DATG'] - UNITE_MGIB = EXEC_MAILLAGE['UNITE_MGIB'] - NIVE_GIBI = EXEC_MAILLAGE['NIVE_GIBI'] - -# 1.4 ==> Creation du repertoire pour l'execution du logiciel GIBI - - erreur_partiel = [0] - Rep_Calc_ASTER = os.getcwd() - - Nom_Rep_local_mail = "tmp_dgib" - Rep_Calc_LOGICIEL_local_mail = os.path.join(".",Nom_Rep_local_mail) - Rep_Calc_LOGICIEL_global_mail = os.path.join(Rep_Calc_ASTER,Nom_Rep_local_mail) - - try : - os.mkdir(Rep_Calc_LOGICIEL_global_mail) - except os.error,erreur_partiel : - self.cr.warn("Code d'erreur de mkdir : " + str(erreur_partiel[0]) + " : " + erreur_partiel[1]) - self.cr.fatal("Impossible de creer le repertoire de travail pour le logiciel de maillage : "+Rep_Calc_LOGICIEL_global_mail) - - aux_datg = 'fort.'+str(UNITE_DATG) - fichier_datg = os.path.join(Rep_Calc_LOGICIEL_global_mail,aux_datg) - - aux_mgib = 'fort.'+str(UNITE_MGIB) - fichier_mgib = os.path.join(Rep_Calc_ASTER,aux_mgib) - - repertoire_outils = aster.repout() - if (LOGICIEL == 'GIBI2000') : logi_mail = repertoire_outils+'gibi2000' - if (LOGICIEL == 'GIBI98') : logi_mail = repertoire_outils+'gibi98' - -# 1.5 ==> Construction du maillage et du modele de reference - - if (MODELISATION == '3D') and (FATIGUE != None) : - - H_IMMERGEE = MONOPODE['H_BASE'] - - mail_eolienne(H_TOTALE, H_BASE, H_IMMERGEE, H_MOYEU, H_JONCTION, DECAL_PALES, - DEXT_NACELLE, EPAIS_NACELLE, DEXT_HAUT_BASE, DEXT_BAS_BASE, - EPAIS_HAUT_BASE, EPAIS_BAS_BASE, DEXT_HAUT_FUT, DEXT_BAS_FUT, - EPAIS_HAUT_FUT, EPAIS_BAS_FUT, NB_ELEM_BASE, NB_ELEM_FUT, - NBEL_EPAIS_BASE, NBEL_EPAIS_FUT, NBEL_DCIR_BASE, NBEL_DCIR_FUT, - ANGLE_VENT_AXE_X, - MODELISATION, TYPE_ELEM, NIVE_GIBI, fichier_datg) - - EXEC_LOGICIEL( - LOGICIEL=logi_mail, - ARGUMENT=(fichier_datg, # fichier de donnees GIBI - fichier_mgib, # fichier resultats format GIBI - ) - ) - - PRE_GIBI() - - if NOM_MAIL_REF!=None : self.DeclareOut('mail_ref',NOM_MAIL_REF) - mail_ref = LIRE_MAILLAGE() - -# debut test -# IMPR_CO(CO=mail_ref,) -# fin test - - MOREF = AFFE_MODELE( MAILLAGE=mail_ref, - AFFE=(_F(GROUP_MA = ('MONOPODE'), - PHENOMENE = 'MECANIQUE', - MODELISATION = '3D',),),); - -# 1.6 ==> Lecture du fichier de resultats STREAM_FM - - (periode_houle,Nb_valeur,Nb_pas_temps,lignes) = lect_resu_stream(INFO) - -# 1.7 ==> declaration de tableaux pour les concepts Aster - - if (MODELISATION == 'COQUE') : - MA2 = [None] * (Nb_pas_temps+1) # pour la modelisation COQUE - - MA = [None] * (Nb_pas_temps+1) # pour les modelisations POUTRE et 3D - __MO = [None] * (Nb_pas_temps+1) - CARA = [None] * (Nb_pas_temps+1) - __affmat = [None] * (Nb_pas_temps+1) - -# 1.8 ==> Construction du dictionnaire contenant : -# pas_de_temps : numeros de ligne du fichier resu_STREAM_FM - - dict_temps = donn_boucle_pas_temps(lignes,Nb_pas_temps) - -#____________________________________________________________________ -# -##################### -# VALEUR TEST -# - test = 'NON' -# Nb_pas_temps = 0 -##################### -#____________________________________________________________________ -# -# 2. ==> BOUCLE SUR LES PAS DE TEMPS -# Dans cette boucle, a chaque pas de temps nous produisons : -# 1. un maillage en fonction de la hauteur d'eau ; -# 2. un chargement correspondant a la hauteur d'eau et a la modelisation ; -# 3. un calcul elastique lineaire avec MECA_STATIQUE ; -# 4. un fichier resultat qui est stocke dans un repertoire .repe ; -# 5. dans le cas ou un calcul en fatigue est demande nous projetons -# le champ de contrainte calcule aux noeuds sur un maillage de reference. -# - - for j in range(Nb_pas_temps+1) : - - k = j + 1 - -# 2.1 ==> Extraction des couples (profondeur,force lineique) -# du fichier resu_STREAM_FM au pas de temps courant et -# remplissage de la liste de travail. - - (range_depart,range_arrive,liste) = extr_char_houle(k,dict_temps,Nb_valeur,lignes) - -# 2.2 ==> Extraction de la hauteur d'eau - - H_IMMERGEE = liste[[(range_arrive-range_depart-2),0]] - if INFO == 2 : - print " ==> Numero d'ordre = ", j - print " ==> hauteur_eau = ", H_IMMERGEE - -##################### -# VALEUR TEST -# -# hauteur_eau = 30. -##################### - print "\n liste = \n", liste - print" " - -# 2.3 ==> Calcul des coefficients de la regression de maniere a -# construire un chargement continu. - - (teta0,teta1,teta2,teta3,alpha1,alpha2,alpha3,beta2,beta3) = eolien_regression (liste, INFO) - - print " " - print " RESULTATS " - print " " - print " teta0 = ", teta0 - print " teta1 = ", teta1 - print " teta2 = ", teta2 - print " teta3 = ", teta3 - print " " - -# 2.4 ==> Creation du maillage pour la hauteur d'eau (H_IMMERGEE) courante - - mail_eolienne(H_TOTALE, H_BASE, H_IMMERGEE, H_MOYEU, H_JONCTION, DECAL_PALES, - DEXT_NACELLE, EPAIS_NACELLE, DEXT_HAUT_BASE, DEXT_BAS_BASE, - EPAIS_HAUT_BASE, EPAIS_BAS_BASE, DEXT_HAUT_FUT, DEXT_BAS_FUT, - EPAIS_HAUT_FUT, EPAIS_BAS_FUT, NB_ELEM_BASE, NB_ELEM_FUT, - NBEL_EPAIS_BASE, NBEL_EPAIS_FUT, NBEL_DCIR_BASE, NBEL_DCIR_FUT, - ANGLE_VENT_AXE_X, - MODELISATION, TYPE_ELEM, NIVE_GIBI, fichier_datg) - -# 2.5 ==> Lancement de GIBI - EXEC_LOGICIEL( - LOGICIEL = logi_mail, - ARGUMENT = (fichier_datg, # fichier de donnees GIBI - fichier_mgib, # fichier resultats format GIBI - ) - ) - -# 2.6 ==> Lecture du maillage et definition des groupes - - PRE_GIBI() - - MA[j] = LIRE_MAILLAGE() - - MA[j]=DEFI_GROUP( reuse = MA[j], - MAILLAGE = MA[j], - CREA_GROUP_NO = _F( TOUT_GROUP_MA='OUI',),); - -# debut test -# IMPR_CO(CO=MA[j],) -# fin test - -# 2.7 ==> Modelisation POUTRE - - if MODELISATION == 'POUTRE' : - - __MO[j]=AFFE_MODELE(MAILLAGE=MA[j], - AFFE=_F(GROUP_MA='EOLIENNE',PHENOMENE='MECANIQUE',MODELISATION='POU_D_T',),); - - motscle={} - motscle['POUTRE']=[] - for i in range(NB_ELEM_FUT) : - nom = 'FUT'+str(i+1) - incr = (DEXT_BAS_FUT - DEXT_HAUT_FUT)/(2.0*NB_ELEM_FUT) - r1 = (DEXT_BAS_FUT/2.0) - (i*incr) - r2 = r1 - incr - motscle['POUTRE'].append(_F(GROUP_MA=nom,SECTION='CERCLE',CARA=('R1','R2','EP1','EP2',),VALE=(r1,r2,EPAIS_BAS_FUT,EPAIS_HAUT_FUT,),VARI_SECT='HOMOTHETIQUE',), ) - - for i in range(NB_ELEM_BASE) : - nom = 'BASE'+str(i+1) - incr = (DEXT_BAS_BASE - DEXT_HAUT_BASE)/(2.0*NB_ELEM_BASE) - r1 = (DEXT_BAS_BASE/2.0) - (i*incr) - r2 = r1 - incr - motscle['POUTRE'].append(_F(GROUP_MA=nom,SECTION='CERCLE',CARA=('R1','R2','EP1','EP2',),VALE=(r1,r2,EPAIS_BAS_BASE,EPAIS_HAUT_BASE,),VARI_SECT='HOMOTHETIQUE',), ) - - CARA[j]=AFFE_CARA_ELEM( MODELE = __MO[j], - **motscle ); - -# 2.8 ==> Modelisation COQUE - - if MODELISATION == 'COQUE' : - - MA2[j] = CREA_MAILLAGE( MAILLAGE=MA[j], - MODI_MAILLE=( _F( OPTION = 'QUAD8_9', - GROUP_MA = ('PARTEM','PARTIM',),), - _F( OPTION = 'TRIA6_7', - GROUP_MA = ('JONCTION',),),), - ); - - __MO[j] = AFFE_MODELE( MAILLAGE=MA2[j], - AFFE=( _F( GROUP_MA = ('PARTEM','PARTIM','JONCTION','CHAUTE'), - PHENOMENE = 'MECANIQUE', - MODELISATION = 'COQUE_3D',), - _F( GROUP_MA = 'NACELLE', - PHENOMENE = 'MECANIQUE', - MODELISATION = 'POU_D_E',),), - ); - - - MA2[j] = MODI_MAILLAGE( reuse = MA2[j], - MAILLAGE = MA2[j], - ORIE_NORM_COQUE = _F( - GROUP_MA = ('PARTEM','PARTIM','JONCTION'),),); - - CARA[j] = AFFE_CARA_ELEM( MODELE=__MO[j], - POUTRE=( _F(GROUP_MA = 'NACELLE', - SECTION = 'CERCLE', - CARA = ('R','EP',), - VALE = (dex_nacelle/2.,ep_nacelle,), ), - ), - COQUE=( _F( GROUP_MA = ('PARTEM','PARTIM','CHAUTE'), - EPAIS = ep_b_fut, - ANGL_REP = (0.0,90.0,), ), - - _F( GROUP_MA = ('JONCTION'), - EPAIS = h_jonction, ), - ), - ); - -# 2.9 ==> Modelisation 3D - - if MODELISATION == '3D' : - - __MO[j] = AFFE_MODELE( MAILLAGE=MA[j], - AFFE=(_F( GROUP_MA = ('BASE','FUT','JONCTION','CHAUTE','SI1','SE1'), - PHENOMENE = 'MECANIQUE', - MODELISATION = '3D',), - _F( GROUP_MA ='NACELLE', - PHENOMENE ='MECANIQUE', - MODELISATION ='POU_D_E',),), - ); - - MA[j] = MODI_MAILLAGE( reuse = MA[j], - MAILLAGE = MA[j], - ORIE_PEAU_3D = _F( - GROUP_MA = ('SE1','SI1','CHAUTE'),), - ); - - CARA[j] = AFFE_CARA_ELEM( MODELE =__MO[j], - POUTRE =( - _F( GROUP_MA = 'NACELLE', - SECTION = 'CERCLE', - CARA = ('R','EP',), - VALE = (DEXT_NACELLE/2.0,EPAIS_NACELLE,), ), - ), - ); - -# 2.10 ==> Affectation du materiau - - motscles={} - motscles['AFFE_MATERIAU']=[] - for mat in affemateriau : - if mat['TOUT'] == None : - # Creation de mots-cles pour les AFFE_CHAR_MECA - motscles['AFFE_MATERIAU'].append(_F( GROUP_MA = mat['GROUP_MA'], - MATER = mat['MATER'], - TEMP_REF = mat['TEMP_REF'],) ) - else : - # Creation de mots-cles pour les AFFE_CHAR_MECA - motscles['AFFE_MATERIAU'].append(_F( TOUT = 'OUI', - MATER = mat['MATER'], - TEMP_REF = mat['TEMP_REF'],) ) - if MODELISATION == 'COQUE' : - __affmat[j] = AFFE_MATERIAU( MAILLAGE = MA2[j], - MODELE = __MO[j], - AFFE = motscles['AFFE_MATERIAU'], - ) - else : - __affmat[j] = AFFE_MATERIAU( MAILLAGE = MA[j], - MODELE = __MO[j], - AFFE = motscles['AFFE_MATERIAU'], - ) - -# 2.11 ==> Chargement et conditions aux limites - - RAUMER = 1027.42 # masse volumique de l'eau de mer (kg/m3) - l_elem_stream = 0.3 # longueur des elements de STREAM_FM (m) - - if test == 'OUI': - # FC3 poutre - if MODELISATION == 'POUTRE' : - FC3 = FORMULE(NOM_PARA=('X','Y','Z'),VALE=' -(exp((Z+231.21)/20.187))/0.3') - else : - # FC3 coque et 3D - FC3 = FORMULE(NOM_PARA=('X','Y','Z'),VALE='''- ( - (3.E-5-(1.E4*Z))+((-6.E-8*(atan(Y/(X+1.E-8)))*(atan(Y/(X+1.E-8)))*(atan(Y/(X+1.E-8)))*(atan(Y/(X+1.E-8)))+2.E-5*(atan(Y/(X+1.E-8)))*(atan(Y/(X+1.E-8)))*(atan(Y/(X+1.E-8))) - -0.0021*(atan(Y/(X+1.E-8)))*(atan(Y/(X+1.E-8)))+0.0224*(atan(Y/(X+1.E-8)))+0.9328)* - (0.5*'''+str(RAUMER)+'''*1.6**2)))''') - else : - if MODELISATION == 'POUTRE' : - FC3 = FORMULE(NOM_PARA=('X','Y','Z'),VALE=''' -(''' - +str(teta0)+'''+(''' - +str(teta1)+''')*(Z-('''+str(alpha1)+'''))+(''' - +str(teta2)+''')*((Z-('''+str(alpha2)+'''))*(Z-('''+str(alpha1)+'''))-('''+str(beta2)+'''))+(''' - +str(teta3)+''')*( (Z-('''+str(alpha3)+'''))*((Z-('''+str(alpha2)+'''))*(Z-('''+str(alpha1)+'''))-(''' - +str(beta2)+'''))-('''+str(beta3)+''')*(Z-('''+str(alpha1)+'''))))/'''+str(l_elem_stream)) - else : - r_bas = (DEXT_HAUT_BASE + DEXT_BAS_FUT)/4.0 # rayon moyen de la base - deux_pi_r_bas = 2.0*math.pi*r_bas # rayon moyen de la base multiplie par 2*pi - int_dp_etoil = -4.83893 # valeur de l integrale de la fonction de repartition de pression - - FC3 = FORMULE(NOM_PARA=('X','Y','Z'),VALE=''' -( - (('''+str(H_BASE)+'''-Z)*1.0E+4)+( - ((('''+str(teta0)+'''+''' - +str(teta1)+'''*(Z-'''+str(alpha1)+''')+''' - +str(teta2)+'''*((Z-'''+str(alpha2)+''')*(Z-'''+str(alpha1)+''')-'''+str(beta2)+''')+''' - +str(teta3)+'''*( (Z-'''+str(alpha3)+''')*((Z-'''+str(alpha2)+''')*(Z-'''+str(alpha1)+''')-''' - +str(beta2)+''')-'''+str(beta3)+'''*(Z-'''+str(alpha1)+''')))/'''+str(l_elem_stream)+''')-''' - +str(deux_pi_r_bas)+'''*(('''+str(H_BASE)+'''-Z)*1.0E+4))* - ((-6.E-8*(atan(Y/(X+1.E-8)))*(atan(Y/(X+1.E-8)))*(atan(Y/(X+1.E-8)))*(atan(Y/(X+1.E-8)))+2.E-5*(atan(Y/(X+1.E-8)))*(atan(Y/(X+1.E-8)))*(atan(Y/(X+1.E-8))) - -0.0021*(atan(Y/(X+1.E-8)))*(atan(Y/(X+1.E-8)))+0.0224*(atan(Y/(X+1.E-8)))+0.9328))/('''+str(r_bas)+'''*'''+str(int_dp_etoil)+''')))''') - - if CHARGEMENT['VENT'] == 'OUI' : - FV0 = CHARGEMENT['FORCE_VENT_FUT'] - else : - FV0 = FORMULE(NOM_PARA=('X','Y','Z'),VALE='0.0*Z') - - if MODELISATION == 'POUTRE' : - CH=AFFE_CHAR_MECA_F(MODELE=__MO[j], - FORCE_POUTRE=(_F(GROUP_MA='PARTIM',FX=FC3,), - _F(GROUP_MA='PARTEM',FX=FV0,),),) - if MODELISATION == 'COQUE' : - CH=AFFE_CHAR_MECA_F(MODELE=__MO[j], - FORCE_COQUE=(_F(GROUP_MA='SI1',PRES=FC3,), - _F(GROUP_MA='SE1',PRES=FV0,),),); - - if MODELISATION == '3D' : - CH=AFFE_CHAR_MECA_F(MODELE=__MO[j], - PRES_REP=(_F(GROUP_MA='SI1',PRES=FC3,), - _F(GROUP_MA='SE1',PRES=FV0,),),); - - # force due au poids du rotor decale de d1 (N) - F2 = CHARGEMENT['FORCE_POIDS_ROTOR'] - - # force due au poids de la nacelle (N) - F3 = CHARGEMENT['FORCE_POIDS_NACELLE'] - - # force totale en z sur le sommet - FCZ = F2+F3 - - # force du à l'effort du vent sur les pales - FRU = CHARGEMENT['FORCE_VENT_PALES'] - # moment resistant - MRU = CHARGEMENT['MOMENT_RESISTANT'] - - # force et moment dus au vent sur le rotor suivant le repère global - ALPHAR = CHARGEMENT['ANGLE_VENT_AXE_X']*(math.pi)/180.0 - - F1X = FRU*math.cos(ALPHAR) - F1Y = FRU*math.sin(ALPHAR) - M1X = MRU*math.cos(ALPHAR) - M1Y = MRU*math.sin(ALPHAR) - - MCY = M1Y-(MONOPODE['DECAL_PALES']*F2)+(MONOPODE['H_MOYEU']*FRU) - - if MODELISATION == 'POUTRE' : - LIMIT=AFFE_CHAR_MECA( MODELE = __MO[j], - DDL_IMPO = _F( GROUP_NO='B_BASE', - DX=0.0,DY=0.0,DZ=0.0, - DRX=0.0,DRY=0.0,DRZ=0.0,), - FORCE_NODALE = _F( GROUP_NO='H_FUT', - FX=F1X, - FY=F1Y, - FZ=FCZ, - MX=M1X, - MY=MCY, - MZ=0.0,),) - - if MODELISATION == 'COQUE' : - LIMIT=AFFE_CHAR_MECA(MODELE=__MO[j], - DDL_IMPO=_F(GROUP_NO='CBASI', - DX=0.0,DY=0.0,DZ=0.0, - DRX=0.0,DRY=0.0,DRZ=0.0,), - - LIAISON_ELEM=_F(OPTION='COQ_POU', - CARA_ELEM = CARA[j], - AXE_POUTRE=(0.,0.,1.,), - GROUP_MA_1='CHAUTE', - GROUP_NO_2='H_FUT',), - - FORCE_NODALE=(_F(GROUP_NO='CHP', - FX=F1X,FY=F1Y,FZ=F2, - MX=M1X,MY=M1Y,MZ=0.0,), - - _F(GROUP_NO='CHP0',FZ=F3,), - ),) - - if MODELISATION == '3D' : - LIMIT=AFFE_CHAR_MECA(MODELE=__MO[j], - DDL_IMPO=_F(GROUP_NO='CBASI', - DX=0.0,DY=0.0,DZ=0.0,), - - LIAISON_ELEM=_F(OPTION='3D_POU', - CARA_ELEM = CARA[j], - AXE_POUTRE=(0.,0.,1.,), - GROUP_MA_1='CHAUTE', - GROUP_NO_2='H_FUT',), - - FORCE_NODALE=(_F(GROUP_NO='CHP', - FX=F1X,FY=F1Y,FZ=F2, - MX=M1X,MY=M1Y,MZ=0.0,), - - _F(GROUP_NO='CHP0',FZ=F3,), - ),) - - POIDS=AFFE_CHAR_MECA( MODELE=__MO[j], - PESANTEUR=(9.81,0.0,0.0,-1.0,),) - -# 2.12 ==> Realisation du calcul - - if MODELISATION == 'POUTRE' : - - TEMPS=DEFI_LIST_REEL(DEBUT=0.0, - INTERVALLE=_F(JUSQU_A=1.0, - PAS=1.0,),) - - RESU=STAT_NON_LINE(MODELE=__MO[j], - CHAM_MATER=__affmat[j], - CARA_ELEM=CARA[j], - EXCIT=(_F(CHARGE=POIDS,), - _F(CHARGE=CH,), - _F(CHARGE=LIMIT,),), - COMP_INCR=_F(RELATION='ELAS', - GROUP_MA='EOLIENNE',), - INCREMENT=_F(LIST_INST=TEMPS, - NUME_INST_FIN=1,),) - - RESU=CALC_ELEM( reuse =RESU, - RESULTAT=RESU, - OPTION=('SIEF_ELNO_ELGA','SIGM_ELNO_SIEF','SIPO_ELNO_SIEF',),) - - if MODELISATION == 'COQUE' : - RESU=MECA_STATIQUE( MODELE=__MO[j], - CHAM_MATER=__affmat[j], - CARA_ELEM=CARA[j], - EXCIT=(_F(CHARGE=POIDS,), - _F(CHARGE=CH,), - _F(CHARGE=LIMIT,),), - NIVE_COUCHE='MOY', - ); - RESU=CALC_ELEM( reuse =RESU, - RESULTAT=RESU, - OPTION=('SIGM_ELNO_DEPL','EQUI_ELNO_SIGM',),) - - RESU = CALC_NO( reuse =RESU, - RESULTAT=RESU, - OPTION=('SIGM_NOEU_DEPL','EQUI_NOEU_SIGM',),); - - if MODELISATION == '3D' : - RESU=MECA_STATIQUE( MODELE=__MO[j], - CHAM_MATER=__affmat[j], - CARA_ELEM=CARA[j], - EXCIT=(_F(CHARGE=POIDS,), - _F(CHARGE=CH,), - _F(CHARGE=LIMIT,),), - ); - RESU=CALC_ELEM( reuse =RESU, - RESULTAT=RESU, - REPE_COQUE=_F(NIVE_COUCHE='MOY',), - OPTION=('SIGM_ELNO_DEPL','EQUI_ELNO_SIGM',)); - - RESU = CALC_NO( reuse =RESU, - RESULTAT=RESU, - OPTION=('SIGM_NOEU_DEPL','EQUI_NOEU_SIGM',),); - -# 2.13 ==> Preparation du modele de reference si modelisation 3D calcul de la fatigue - - delta = periode_houle/Nb_pas_temps - inst = -periode_houle/2.0 + j*delta - if (MODELISATION == '3D') and (FATIGUE != None) : - - if (k == 1) : - CHAMREF = AFFE_MATERIAU( MAILLAGE = mail_ref, - MODELE = MOREF, - AFFE = motscles['AFFE_MATERIAU'],) - - RESPRO = PROJ_CHAMP( METHODE = 'ELEM', - NOM_CHAM = 'SIGM_NOEU_DEPL', - RESULTAT = RESU, - MODELE_1 = __MO[j], - MODELE_2 = MOREF, - VIS_A_VIS=( - _F( GROUP_MA_2='MONOPODE', - GROUP_MA_1='MONOPODE' ), - ), - ) - - SIG_PRO = CREA_CHAMP( TYPE_CHAM = 'NOEU_SIEF_R', - OPERATION = 'EXTR', - RESULTAT = RESPRO , - NOM_CHAM = 'SIGM_NOEU_DEPL', - NUME_ORDRE = 1, - ) - - if (k==1) : - RESREF = CREA_RESU( - OPERATION = 'AFFE', - TYPE_RESU = 'EVOL_ELAS', - NOM_CHAM = 'SIGM_NOEU_DEPL', - AFFE = _F( CHAM_GD = SIG_PRO, - INST = (inst), ), - ) - else : - RESREF = CREA_RESU( reuse = RESREF, - OPERATION = 'AFFE', - TYPE_RESU = 'EVOL_ELAS', - NOM_CHAM = 'SIGM_NOEU_DEPL', - AFFE = _F( CHAM_GD = SIG_PRO, - INST = (inst), ), - ) - -# 2.14 ==> Impression des resultats - - if MODELISATION == 'POUTRE' : - fich1='poutre_t='+str(inst)+'.resu' - fich2='poutre_t='+str(inst)+'.cast' - fich3='poutre_t='+str(inst)+'.ensi' - fich4='poutre_t='+str(inst)+'.unv' - if MODELISATION == 'COQUE' : - fich1='coque_t='+str(inst)+'.resu' - fich2='coque_t='+str(inst)+'.cast' - fich3='coque_t='+str(inst)+'.ensi' - fich4='coque_t='+str(inst)+'.unv' - if MODELISATION == '3D' : - fich1='3D_t='+str(inst)+'.resu' - fich2='3D_t='+str(inst)+'.cast' - fich3='3D_t='+str(inst)+'.ensi' - fich4='3D_t='+str(inst)+'.unv' - - fich1b = './REPE_OUT/'+fich1 - fich2b = './REPE_OUT/'+fich2 - fich3b = './REPE_OUT/'+fich3 - fich4b = './REPE_OUT/'+fich4 - - if IMPRESSION != None : - motscles={} - motscles['IMPRESSION']=[] - # Creation de mots-cles pour les IMPR_RESU - for impr in IMPRESSION : - if impr['FORMAT']=='RESULTAT': - UNIT_1B=DEFI_FICHIER(FICHIER=fich1b) - unitr = UNIT_1B - if impr['FORMAT']=='CASTEM': - UNIT_2B=DEFI_FICHIER(FICHIER=fich2b) - unitr = UNIT_2B - if impr['FORMAT']=='ENSIGHT': - UNIT_3B=DEFI_FICHIER(FICHIER=fich3b) - unitr = UNIT_3B - if impr['FORMAT']=='IDEAS': - UNIT_4B=DEFI_FICHIER(FICHIER=fich4b) - unitr = UNIT_4B - if MODELISATION == '3D': - motscles['IMPRESSION'].append(_F(MAILLAGE=MA[j],RESULTAT=RESU, - NOM_CHAM=('DEPL','SIGM_ELNO_DEPL','EQUI_ELNO_SIGM',),) ) - if MODELISATION == 'COQUE': - motscles['IMPRESSION'].append(_F(MAILLAGE=MA2[j],RESULTAT=RESU, - NOM_CHAM=('DEPL','SIGM_ELNO_DEPL','EQUI_ELNO_SIGM',),) ) - if MODELISATION == 'POUTRE': - motscles['IMPRESSION'].append(_F(MAILLAGE=MA[j],RESULTAT=RESU, - NOM_CHAM=('DEPL','SIGM_ELNO_SIEF','SIPO_ELNO_SIEF',),) ) - - IMPR_RESU(FORMAT=impr['FORMAT'],UNITE=unitr, - RESU=motscles['IMPRESSION'],) - - for impr in IMPRESSION : - if impr['FORMAT']=='RESULTAT': - DEFI_FICHIER(ACTION='LIBERER',FICHIER=fich1b) - DETRUIRE(CONCEPT=_F( NOM = UNIT_1B)) - if impr['FORMAT']=='CASTEM': - DEFI_FICHIER(ACTION='LIBERER',FICHIER=fich2b) - DETRUIRE(CONCEPT=_F( NOM = UNIT_2B)) - if impr['FORMAT']=='ENSIGHT': - DEFI_FICHIER(ACTION='LIBERER',FICHIER=fich3b) - DETRUIRE(CONCEPT=_F( NOM = UNIT_3B)) - if impr['FORMAT']=='IDEAS': - DEFI_FICHIER(ACTION='LIBERER',FICHIER=fich4b) - DETRUIRE(CONCEPT=_F( NOM = UNIT_4B)) - - if (MODELISATION == '3D') and (FATIGUE != None) : - DETRUIRE(CONCEPT=_F( NOM = SIG_PRO)) - DETRUIRE(CONCEPT=_F( NOM = RESPRO)) - if MODELISATION == 'POUTRE' : - DETRUIRE(CONCEPT=_F( NOM = TEMPS)) - - DETRUIRE(CONCEPT=_F( NOM = FC3)) - DETRUIRE(CONCEPT=_F( NOM = CH)) - DETRUIRE(CONCEPT=_F( NOM = LIMIT)) - DETRUIRE(CONCEPT=_F( NOM = POIDS)) - DETRUIRE(CONCEPT=_F( NOM = RESU)) -# -#____________________________________________________________________ -# -# 3. Calcul de fatigue. -# On calcule la fatigue si la modelisation est 3D et si le mot clef -# fatigue est present. -#____________________________________________________________________ -# -# 3.1 ==> Calcul de la fatigue -# - if (MODELISATION == '3D') and (FATIGUE != None) : - - self.DeclareOut('CHFATI',self.sd) - CHFATI = CALC_FATIGUE ( - TYPE_CALCUL = 'FATIGUE_MULTI', - TYPE_CHARGE = 'PERIODIQUE', - OPTION = 'DOMA_NOEUD', - RESULTAT = RESREF, - CHAM_MATER = CHAMREF, - GROUP_MA = ('BASE','FUT'), - MAILLAGE = mail_ref, - CRITERE=FATIGUE['CRITERE'], - METHODE='CERCLE_EXACT', - INFO = 2, ) - -#____________________________________________________________________ -# -# 3.2 ==> Impression des resultats de fatigue -# - if IMPRESSION != None : - motscles={} - motscles['IMPRESSION']=[] - - motscles['IMPRESSION'].append(_F(MAILLAGE=mail_ref,CHAM_GD=CHFATI,) ) - - IMPR_RESU( FORMAT=impr['FORMAT'], - MODELE = MOREF, - RESU=motscles['IMPRESSION'],) - -#____________________________________________________________________ -# -# 4. C'est fini ! -#____________________________________________________________________ -# - if erreur : - if not messages_erreur.has_key(erreur) : - erreur = 100 - self.cr.fatal(messages_erreur[erreur]) - - return -# -#____________________________________________________________________ -#____________________________________________________________________ -# -# CATALOGUES DES MACRO-COMMANDES -#____________________________________________________________________ -#____________________________________________________________________ -# -# ________________________________________ -# -#____________________________________________________________________ -#____________________________________________________________________ -# -# CATALOGUE DE LA MACRO COMMANDE CALC_CHAR_HOULE -#____________________________________________________________________ -#____________________________________________________________________ -# - -CALC_CHAR_HOULE=MACRO( nom="CALC_CHAR_HOULE",op=calc_char_houle_ops, - fr="Calcul le chargement du a la houle.", - ang=".",reentrant='n', - docu="Ux.xx.xx-a", - - STREAM =FACT(statut='o',max=1, - PROFONDEUR =SIMP(statut='o',typ='R'), - H_HOULE =SIMP(statut='o',typ='R'), - PERI_HOULE =SIMP(statut='o',typ='R'), - COUR_EULERIEN =SIMP(statut='o',typ='R'), - COEF_TRAINEE =SIMP(statut='o',typ='R'), - COEF_INERTIE =SIMP(statut='o',typ='R'), - ORDR_FONC_COURAN =SIMP(statut='o',typ='I'), - NB_POINTS_VERT =SIMP(statut='o',typ='I'), - NB_INTER_PERI =SIMP(statut='o',typ='I'), - DEXT_HAUT_BASE =SIMP(statut='o',typ='R'), - ), - - IMPRESSION =FACT(statut='f', - UNITE =SIMP(statut='o',typ='I'), - ), - - INFO = SIMP(statut='f',typ='I',defaut=1,into=(1,2)), - -); - -# -#____________________________________________________________________ -#____________________________________________________________________ -# -# CATALOGUE DE LA MACRO COMMANDE MACR_CALC_EOLIENNE -#____________________________________________________________________ -#____________________________________________________________________ -# - -def macr_calc_eolienne_prod(self,NOM_MAIL_REF,**args): - if NOM_MAIL_REF != None : self.type_sdprod(NOM_MAIL_REF,maillage_sdaster) - return cham_no_sdaster - - -MACR_CALC_EOLIENNE=MACRO(nom="MACR_CALC_EOLIENNE",op=macr_calc_eolienne_ops, - sd_prod=macr_calc_eolienne_prod, - fr="Calcul d une eolienne en mer.", - ang=".",reentrant='n', - docu="U2.09.04-a", - - EXEC_MAILLAGE =FACT(statut='o', - LOGICIEL =SIMP(statut='o',typ='TXM',defaut="GIBI2000",into=("GIBI98","GIBI2000") ), - UNITE_DATG =SIMP(statut='f',typ='I',defaut=70), - UNITE_MGIB =SIMP(statut='f',typ='I',defaut=19), - NIVE_GIBI =SIMP(statut='f',typ='I',defaut=10,into=(3,4,5,6,7,8,9,10,11)), - ), - - MODELISATION =SIMP(statut='o',typ='TXM', into=("POUTRE","COQUE","3D") ), - NOM_MAIL_REF =SIMP(statut='f',typ=(CO,maillage_sdaster)), - - TYPE_ELEM =SIMP(statut='f',typ='TXM',defaut="CUB8",into=("CUB8","CU20") ), - - b_model_3D =BLOC(condition = "MODELISATION == '3D'", - - MONOPODE =FACT(statut='o',max=1, - - H_TOTALE =SIMP(statut='o',typ='R' ), - H_BASE =SIMP(statut='o',typ='R' ), - H_MOYEU =SIMP(statut='o',typ='R' ), - H_JONCTION =SIMP(statut='o',typ='R' ), - DECAL_PALES =SIMP(statut='o',typ='R' ), - DEXT_NACELLE =SIMP(statut='o',typ='R' ), - EPAIS_NACELLE =SIMP(statut='o',typ='R' ), - DEXT_HAUT_BASE =SIMP(statut='o',typ='R' ), - DEXT_BAS_BASE =SIMP(statut='f',typ='R' ), - EPAIS_HAUT_BASE =SIMP(statut='o',typ='R' ), - EPAIS_BAS_BASE =SIMP(statut='f',typ='R' ), - DEXT_HAUT_FUT =SIMP(statut='o',typ='R' ), - DEXT_BAS_FUT =SIMP(statut='f',typ='R' ), - EPAIS_HAUT_FUT =SIMP(statut='o',typ='R' ), - EPAIS_BAS_FUT =SIMP(statut='f',typ='R' ), - NB_ELEM_BASE =SIMP(statut='f',typ='I',defaut=30), - NB_ELEM_FUT =SIMP(statut='f',typ='I',defaut=70), - NBEL_EPAIS_BASE =SIMP(statut='f',typ='I',defaut=3), - NBEL_EPAIS_FUT =SIMP(statut='f',typ='I',defaut=3), - NBEL_DCIR_BASE =SIMP(statut='f',typ='I',defaut=15), - NBEL_DCIR_FUT =SIMP(statut='f',typ='I',defaut=15), - ), - ), - - b_model_coque =BLOC(condition = "MODELISATION == 'COQUE' ", - - MONOPODE =FACT(statut='o',max=1, - - H_TOTALE =SIMP(statut='o',typ='R' ), - H_BASE =SIMP(statut='o',typ='R' ), - H_MOYEU =SIMP(statut='o',typ='R' ), - H_JONCTION =SIMP(statut='o',typ='R' ), - DECAL_PALES =SIMP(statut='o',typ='R' ), - DEXT_NACELLE =SIMP(statut='o',typ='R' ), - EPAIS_NACELLE =SIMP(statut='o',typ='R' ), - DEXT_HAUT_BASE =SIMP(statut='o',typ='R' ), - DEXT_BAS_BASE =SIMP(statut='f',typ='R' ), - EPAIS_HAUT_BASE =SIMP(statut='o',typ='R' ), - EPAIS_BAS_BASE =SIMP(statut='f',typ='R' ), - DEXT_HAUT_FUT =SIMP(statut='o',typ='R' ), - DEXT_BAS_FUT =SIMP(statut='f',typ='R' ), - EPAIS_HAUT_FUT =SIMP(statut='o',typ='R' ), - EPAIS_BAS_FUT =SIMP(statut='f',typ='R' ), - NB_ELEM_BASE =SIMP(statut='f',typ='I',defaut=30), - NB_ELEM_FUT =SIMP(statut='f',typ='I',defaut=70), - NBEL_DCIR_BASE =SIMP(statut='f',typ='I',defaut=15), - NBEL_DCIR_FUT =SIMP(statut='f',typ='I',defaut=15), - ), - ), - - b_model_poutre =BLOC(condition = "MODELISATION == 'POUTRE' ", - - MONOPODE =FACT(statut='o',max=1, - - H_TOTALE =SIMP(statut='o',typ='R' ), - H_BASE =SIMP(statut='o',typ='R' ), - H_MOYEU =SIMP(statut='o',typ='R' ), - DECAL_PALES =SIMP(statut='o',typ='R' ), - DEXT_HAUT_BASE =SIMP(statut='o',typ='R' ), - DEXT_BAS_BASE =SIMP(statut='f',typ='R' ), - EPAIS_HAUT_BASE =SIMP(statut='o',typ='R' ), - EPAIS_BAS_BASE =SIMP(statut='f',typ='R' ), - DEXT_HAUT_FUT =SIMP(statut='o',typ='R' ), - DEXT_BAS_FUT =SIMP(statut='f',typ='R' ), - EPAIS_HAUT_FUT =SIMP(statut='o',typ='R' ), - EPAIS_BAS_FUT =SIMP(statut='f',typ='R' ), - NB_ELEM_BASE =SIMP(statut='f',typ='I',defaut=30), - NB_ELEM_FUT =SIMP(statut='f',typ='I',defaut=70), - ), - ), - - AFFE_MATERIAU =FACT(statut='o',max=3, - regles=(UN_PARMI('TOUT','GROUP_MA'),), - TOUT =SIMP(statut='f',typ='TXM',into=("OUI",) ), - GROUP_MA =SIMP(statut='f',typ='TXM',into=("BASE","FUT") ), - MATER =SIMP(statut='o',typ=mater_sdaster ), - TEMP_REF =SIMP(statut='f',typ='R',defaut= 0.E+0 ), - ), - - CHARGEMENT =FACT(statut='o', - FORCE_POIDS_ROTOR =SIMP(statut='o',typ='R' ), - FORCE_POIDS_NACELLE =SIMP(statut='o',typ='R' ), - FORCE_VENT_PALES =SIMP(statut='o',typ='R' ), - ANGLE_VENT_AXE_X =SIMP(statut='o',typ='R' ), - MOMENT_RESISTANT =SIMP(statut='o',typ='R' ), - FORCE_VENT_FUT =SIMP(statut='o',typ=(fonction_sdaster,formule) ), - VENT =SIMP(statut='o',typ='TXM',into=("OUI","NON") ), - HOULE =SIMP(statut='o',typ='TXM',into=("OUI","NON") ), - ), - - FATIGUE =FACT(statut='f', - CRITERE =SIMP(statut='f',typ='TXM',defaut="DANG_VAN_MODI_AC",into=("MATAKE","DANG_VAN_MODI_AC") ), - ), - - SOLVEUR =FACT(statut='d', - METHODE =SIMP(statut='f',typ='TXM',defaut="MULT_FRONT",into=("MULT_FRONT","LDLT","GCPC") ), - b_mult_front =BLOC(condition = "METHODE == 'MULT_FRONT' ",fr="Paramètres de la méthode multi frontale", - RENUM =SIMP(statut='f',typ='TXM',defaut="METIS",into=("MD","MDA","METIS") ), - ), - b_ldlt =BLOC(condition = "METHODE == 'LDLT' ",fr="Paramètres de la méthode LDLT", - RENUM =SIMP(statut='f',typ='TXM',defaut="RCMK",into=("RCMK","SANS") ), - ), - b_ldlt_mult =BLOC(condition = "METHODE == 'LDLT' or METHODE == 'MULT_FRONT' ", - fr="Paramètres relatifs à la non inversibilité de la matrice à factorise", - NPREC =SIMP(statut='f',typ='I',defaut= 8 ), - STOP_SINGULIER =SIMP(statut='f',typ='TXM',defaut="OUI",into=("OUI","NON") ), - ), - b_gcpc =BLOC(condition = "METHODE == 'GCPC' ", fr="Paramètres de la méthode du gradient conjugué", - PRE_COND =SIMP(statut='f',typ='TXM',into=("LDLT_INC",),defaut="LDLT_INC" ), - NIVE_REMPLISSAGE=SIMP(statut='f',typ='I',defaut= 0 ), - RENUM =SIMP(statut='f',typ='TXM',defaut="RCMK",into=("SANS","RCMK") ), - RESI_RELA =SIMP(statut='f',typ='R',defaut= 1.E-6 ), - NMAX_ITER =SIMP(statut='f',typ='I',defaut= 0 ), - ), - SYME =SIMP(statut='f',typ='TXM',defaut="NON",into=("OUI","NON") ), - ), - - IMPRESSION =FACT(statut='f', - FORMAT =SIMP(statut='f',typ='TXM',defaut="RESULTAT", - into=("RESULTAT","CASTEM","IDEAS","ENSIGHT")), - - b_format_ideas =BLOC(condition="FORMAT=='IDEAS'",fr="version Ideas", - VERSION =SIMP(statut='f',typ='I',defaut=5,into=(4,5)), - ), - - b_format_castem =BLOC(condition="FORMAT=='CASTEM'",fr="version Castem", - NIVE_GIBI =SIMP(statut='f',typ='I',defaut=10,into=(3,10)), - ), - - TOUT_ORDRE =SIMP(statut='f',typ='TXM',into=("OUI",) ), - NUME_ORDRE =SIMP(statut='f',typ='I',validators=NoRepeat(),max='**'), - INST =SIMP(statut='f',typ='R',validators=NoRepeat(),max='**'), - ), - - INFO = SIMP(statut='f',typ='I',defaut=1,into=(1,2)), - -); diff --git a/Aster/Cata/cataSTA9/Intranet/macr_cabri_calc_cata.py b/Aster/Cata/cataSTA9/Intranet/macr_cabri_calc_cata.py deleted file mode 100644 index 8cddc463..00000000 --- a/Aster/Cata/cataSTA9/Intranet/macr_cabri_calc_cata.py +++ /dev/null @@ -1,190 +0,0 @@ -#@ MODIF macr_cabri_calc_cata Intranet DATE 28/01/2008 AUTEUR PELLET J.PELLET -# -*- coding: iso-8859-1 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2008 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# ====================================================================== - -from Intranet.macr_cabri_calc_ops import macr_cabri_calc_ops -from Cata.cata import * - -def macr_cabri_calc_prod(self,MODELE_THER,MODELE_MECA,CHAM_MATER, - CHAR_THER,CHAR_MECA,RESU_THER,**args): - if MODELE_THER != None: - self.type_sdprod(MODELE_THER,modele_sdaster) - if MODELE_MECA != None: - self.type_sdprod(MODELE_MECA,modele_sdaster) - if RESU_THER != None: - self.type_sdprod(RESU_THER,evol_ther) - if CHAM_MATER != None: - self.type_sdprod(CHAM_MATER,cham_mater) - if CHAR_THER != None: - for m in CHAR_THER: - self.type_sdprod(m['CHARGE'],char_ther) - if CHAR_MECA != None: - for m in CHAR_MECA: - self.type_sdprod(m['CHARGE'],char_meca) - return evol_noli - - -MACR_CABRI_CALC=MACRO(nom="MACR_CABRI_CALC", - op=macr_cabri_calc_ops, - sd_prod=macr_cabri_calc_prod, - fr="Calcul thermo-mécanique d'une jonction boulonnée de tuyauterie", - reentrant='n', - UIinfo={"groupes":("Outils métier",)}, - MAILLAGE = SIMP(statut='o',typ=maillage_sdaster,), - AFFE_MATERIAU = FACT(statut='o',max='**', - regles=(UN_PARMI('TOUT','GROUP_MA',),), - TOUT = SIMP(statut='f',typ='TXM',into=("OUI",) ), - GROUP_MA = SIMP(statut='f',typ='TXM',into=( - "BRIDE", - "GOUJON", - "ROND", - "ECROU", - "JOINT",) ), - MATER = SIMP(statut='o',typ=mater_sdaster), - TEMP_REF = SIMP(statut='d',typ='R',defaut= 25. ), - ), - CHAM_MATER = SIMP(statut = 'f',typ=CO,), - MODELE_THER= SIMP(statut = 'f',typ=CO,), - - DEFI_CHAR_THER = FACT(statut ='d', - TEMP_INIT = SIMP(statut='d',typ='R',defaut= 25.,), - COEF_H_FLUI = SIMP(statut='f',typ=(fonction_sdaster,nappe_sdaster),), - TEMP_EXT_FLUI = SIMP(statut='f',typ=(fonction_sdaster,nappe_sdaster),), - COEF_H_AIR = SIMP(statut='f',typ=(fonction_sdaster,nappe_sdaster),), - TEMP_EXT_AIR = SIMP(statut='f',typ=(fonction_sdaster,nappe_sdaster),), - LIST_INST = SIMP(statut='f',typ=listr8_sdaster), - ), - - CHAR_THER = FACT(statut = 'f',max=4, - CHARGE = SIMP(statut='o',typ=CO), - TYPE = SIMP(statut='o',typ='TXM', - into=("BRIDE_FLUIDE","BRIDE_AIR","ECROU_GOUJON", - "BRIDE_JOINT"),) - ), - - RESU_THER = SIMP(statut = 'f',typ=CO,), - - - MODELE_MECA= SIMP(statut = 'f',typ=CO,), - - DEFI_CHAR_MECA = FACT(statut='o', - PRETENS = SIMP(statut='f',typ=(fonction_sdaster,nappe_sdaster),), - PRES_REP = SIMP(statut='f',typ=(fonction_sdaster,nappe_sdaster),), - EFFE_FOND = SIMP(statut='f',typ=(fonction_sdaster,nappe_sdaster),), - ), - - CHAR_MECA = FACT(statut = 'f',max=11, - CHARGE = SIMP(statut='o',typ=CO), - TYPE = SIMP(statut='o',typ='TXM', - into=("BLOC_BAS_GOUJ","BLOC_BAS_JOINT", - "BLOC_LAT_ALES","BLOC_LAT_NALES", - "PLAN_TUBE", - "PRES_FLU","EFFET_FOND", - "CONT_JOINT", - "DEFO_THER", - "SERR_ECROU_1","SERR_ECROU_2",),) - ), - - RELATION = SIMP(statut='f',typ='TXM', - into=('VMIS_ISOT_TRAC','ELAS','ELAS_VMIS_TRAC',),), - - SOLVEUR = FACT(statut='d', - METHODE = SIMP(statut='d',typ='TXM',defaut="MULT_FRONT",into=("MULT_FRONT",) ), - b_mult_front = BLOC(condition = "METHODE == 'MULT_FRONT' ", - fr="Paramètres de la méthode multi frontale", - RENUM = SIMP(statut='d',typ='TXM',defaut="METIS",into=("MD","MDA","METIS") ), - NPREC = SIMP(statut='d',typ='I',defaut=8), - STOP_SINGULIER = SIMP(statut='d',typ='TXM',defaut="OUI",into=("OUI","NON") ), - ), - ), - INCREMENT = FACT(statut='f', - regles=(EXCLUS('NUME_INST_INIT','INST_INIT'), - EXCLUS('NUME_INST_FIN','INST_FIN'),), - LIST_INST =SIMP(statut='f',typ=listr8_sdaster), - EVOLUTION =SIMP(statut='f',typ='TXM',defaut="CHRONOLOGIQUE", - into=("CHRONOLOGIQUE",) ), - NUME_INST_INIT =SIMP(statut='f',typ='I'), - INST_INIT =SIMP(statut='f',typ='R'), - NUME_INST_FIN =SIMP(statut='f',typ='I'), - INST_FIN =SIMP(statut='f',typ='R'), - PRECISION =SIMP(statut='f',typ='R',defaut=1.0E-3 ), - # DEBUT DE BLOC POUR LA SUBDIVISION DES PAS DE TEMPS - SUBD_METHODE =SIMP( statut='f',typ='TXM', - into =("AUCUNE","UNIFORME","EXTRAPOLE"), - defaut="AUCUNE", - fr="Méthode de subdivision des pas de temps en cas de non-convergence" - ), - b_subd_unif=BLOC(condition = "SUBD_METHODE == 'UNIFORME'", - regles=(AU_MOINS_UN('SUBD_NIVEAU','SUBD_PAS_MINI'),), - SUBD_COEF_PAS_1=SIMP(statut='f',typ='R',defaut=1.0,val_min=0.0, - fr="Coefficient multiplicateur de la 1ère subdivision"), - SUBD_PAS =SIMP(statut='f',typ='I',defaut=4,val_min=2, - fr="Nombre de subdivision d'un pas de temps"), - SUBD_NIVEAU=SIMP(statut='f',typ='I',val_min=2, - fr="Nombre maximum de niveau de subdivision d'un pas de temps"), - SUBD_PAS_MINI=SIMP(statut='f',typ='R',val_min=0.0, - fr="Pas de temps en dessous duquel on ne subdivise plus"), - ), - b_subd_extr=BLOC(condition = "SUBD_METHODE == 'EXTRAPOLE'", - regles=(AU_MOINS_UN('SUBD_NIVEAU','SUBD_PAS_MINI'),), - SUBD_OPTION =SIMP(statut='f',typ='TXM', - into =("IGNORE_PREMIERES","GARDE_DERNIERES",), - defaut="IGNORE_PREMIERES", - fr="Technique d'extrapolation : les 1ere itérations sont ignorées ou les dernières sont gardées"), - SUBD_ITER_IGNO =SIMP(statut='c',typ='I',defaut=3,val_min=0, - fr="Les n premières itérations sont ignorées pour l'extrapolation"), - SUBD_ITER_FIN =SIMP(statut='c',typ='I',defaut=8,val_min=3, - fr="Seules les n dernières itérations sont prises pour l'extrapolation"), - SUBD_PAS =SIMP(statut='c',typ='I',defaut=4,val_min=2, - fr="Nombre de subdivision d'un pas de temps en cas divergence"), - SUBD_NIVEAU=SIMP(statut='f',typ='I',val_min=2, - fr="Nombre maximum de niveau de subdivision d'un pas de temps"), - SUBD_PAS_MINI=SIMP(statut='f',typ='R',val_min=0.0, - fr="Pas de temps en dessous duquel on ne subdivise plus"), - SUBD_ITER_PLUS =SIMP(statut='c',typ='I',defaut=50,val_min=20, - fr="% itération autorisée en plus"), - ), - # FIN DE BLOC POUR LA SUBDIVISION DES PAS DE TEMPS - OPTI_LIST_INST =SIMP(statut='f',typ='TXM',into=("INCR_MAXI",),), - NOM_CHAM =SIMP(statut='f',typ='TXM',), - NOM_CMP =SIMP(statut='f',typ='TXM',), - VALE =SIMP(statut='f',typ='R'), - ), - NEWTON =FACT(statut='d', - REAC_INCR =SIMP(statut='f',typ='I',defaut= 1 ), - PREDICTION =SIMP(statut='f',typ='TXM',into=("TANGENTE","ELASTIQUE","EXTRAPOL") ), - MATRICE =SIMP(statut='f',typ='TXM',defaut="TANGENTE",into=("TANGENTE","ELASTIQUE") ), - PAS_MINI_ELAS =SIMP(statut='f',typ='R',defaut=0.0E+0), - REAC_ITER =SIMP(statut='f',typ='I',defaut=0), - EVOL_NOLI =SIMP(statut='f',typ=evol_noli), - ), - RESO_INTE =SIMP(statut='f',typ='TXM',defaut="IMPLICITE", - into=("IMPLICITE",)), - CONVERGENCE =FACT(statut='d', - regles=(PRESENT_ABSENT('RESI_REFE_RELA','RESI_GLOB_MAXI','RESI_GLOB_RELA'),), - SIGM_REFE =SIMP(statut='f',typ='R'), - EPSI_REFE =SIMP(statut='f',typ='R'), - FLUX_THER_REFE =SIMP(statut='f',typ='R'), - RESI_REFE_RELA =SIMP(statut='f',typ='R'), - RESI_GLOB_MAXI =SIMP(statut='f',typ='R'), - RESI_GLOB_RELA =SIMP(statut='f',typ='R'), - ITER_GLOB_MAXI =SIMP(statut='f',typ='I',defaut=10), - ITER_GLOB_ELAS =SIMP(statut='f',typ='I',defaut=25), - ), - ); diff --git a/Aster/Cata/cataSTA9/Intranet/macr_cabri_calc_ops.py b/Aster/Cata/cataSTA9/Intranet/macr_cabri_calc_ops.py deleted file mode 100644 index 81d8ea32..00000000 --- a/Aster/Cata/cataSTA9/Intranet/macr_cabri_calc_ops.py +++ /dev/null @@ -1,555 +0,0 @@ -#@ MODIF macr_cabri_calc_ops Intranet DATE 28/01/2008 AUTEUR PELLET J.PELLET -# -*- coding: iso-8859-1 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2008 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# ====================================================================== - - -def macr_cabri_calc_ops(self,MAILLAGE,MODELE_MECA,MODELE_THER,CHAR_THER, - CHAR_MECA,RESU_THER,RESO_INTE, - AFFE_MATERIAU,DEFI_CHAR_THER,DEFI_CHAR_MECA,RELATION,SOLVEUR,CONVERGENCE,NEWTON, - INCREMENT,CHAM_MATER,**args): - """ - Ecriture de la macro MACR_CABRI_CALC - """ - - ################################################################# - ########## PREPARATION MACRO - ################################################################# - - from Accas import _F - - ier =0 - - # On met certains mots-clefs dans des variables locales pour les proteger - affemateriau = AFFE_MATERIAU - mail = MAILLAGE - resointe = RESO_INTE - - # On importe les definitions des commandes a utiliser dans la macro - # Le nom de la variable doit etre obligatoirement le nom de la commande - DEFI_GROUP = self.get_cmd('DEFI_GROUP') - AFFE_MATERIAU = self.get_cmd('AFFE_MATERIAU') - AFFE_MODELE = self.get_cmd('AFFE_MODELE') - MODI_MAILLAGE = self.get_cmd('MODI_MAILLAGE') - AFFE_CHAR_THER_F = self.get_cmd('AFFE_CHAR_THER_F') - AFFE_CHAR_THER = self.get_cmd('AFFE_CHAR_THER') - AFFE_CHAR_MECA_F = self.get_cmd('AFFE_CHAR_MECA_F') - AFFE_CHAR_MECA = self.get_cmd('AFFE_CHAR_MECA') - DEFI_FONCTION = self.get_cmd('DEFI_FONCTION') - DEFI_LIST_REEL = self.get_cmd('DEFI_LIST_REEL') - THER_LINEAIRE = self.get_cmd('THER_LINEAIRE') - STAT_NON_LINE = self.get_cmd('STAT_NON_LINE') - - # La macro compte pour 1 dans la numerotation des commandes - self.set_icmd(1) - - # Le concept sortant (de type evol_noli) est nomme 'resumeca' dans - # le contexte de la macro - self.DeclareOut('resumeca',self.sd) - self.DeclareOut('mail',MAILLAGE) - - ################################################################# - ########## PREPARATION DES MODELES - ################################################################# - - # Definition des groupes - mail=DEFI_GROUP(reuse =mail,MAILLAGE=mail, - CREA_GROUP_NO=( - _F(GROUP_MA='M_GOU',NOM='N_M_GOU',), - _F(GROUP_MA='M_JOI',NOM='N_M_JOI',), - _F(GROUP_MA='SCBJ',NOM='N_SCBJ',), - _F(GROUP_MA='SCJB',NOM='N_SCJB',), - _F(GROUP_MA='M_L_AA',NOM='N_M_L_AA',), - _F(GROUP_MA='SCEG',NOM='N_SCEG',), - _F(GROUP_MA='SCGE',NOM='N_SCGE',),),) - - # Creation du modele thermique - if MODELE_THER != None: - self.DeclareOut('modther',MODELE_THER) - - modther=AFFE_MODELE(MAILLAGE=mail, - AFFE=_F(GROUP_MA=('VTOT','M_GOU','M_TUB','M_JOI','SCBJ','SCJB', - 'M_L_AA','M_INT','M_L_SA','M_EXT','SCEG','SCGE',), - PHENOMENE='THERMIQUE', - MODELISATION='3D_DIAG',), - ); - - # Creation du modele mecanique - if MODELE_MECA != None: - self.DeclareOut('modmeca',MODELE_MECA) - - modmeca = AFFE_MODELE(MAILLAGE=mail, - AFFE=_F(GROUP_MA=('VTOT','M_GOU','M_TUB','M_JOI','SCBJ','SCJB', - 'M_L_AA','M_L_SA','SCEG','SCGE','M_INT','M_EXT',), - PHENOMENE='MECANIQUE', - MODELISATION='3D',), - ); - - # Orientation des mailles - mail=MODI_MAILLAGE(reuse =mail, - MAILLAGE=mail, - ORIE_PEAU_3D=(_F(GROUP_MA=('M_INT','M_TUB',),), - _F(GROUP_MA=('M_L_AA','M_JOI','M_L_SA',),),), - ); - - - - # Affectation des materiaux (thermique) - motscles={} - motscles['AFFE']=[] - for mat in affemateriau: - if mat['TOUT'] == None: - # Creation de mots-cles pour les AFFE_CHAR_MECA - motscles['AFFE'].append(_F(GROUP_MA=mat['GROUP_MA'], - MATER = mat['MATER'])) - else: - # Creation de mots-cles pour les AFFE_CHAR_MECA - motscles['AFFE'].append(_F(TOUT='OUI', - MATER = mat['MATER'])) - - __cham = AFFE_MATERIAU(MAILLAGE=mail, - MODELE=modther, - AFFE=motscles['AFFE'], - ) - - ################################################################# - ########## CONDITIONS AUX LIMITES THERMIQUES - ################################################################# - # Recuperation des parametres thermiques - - if DEFI_CHAR_THER != None: - temp_ini = DEFI_CHAR_THER['TEMP_INIT'] - if DEFI_CHAR_THER['COEF_H_FLUI']!=None: - coef_int = DEFI_CHAR_THER['COEF_H_FLUI'] - else: - coef_int = DEFI_FONCTION(NOM_PARA='INST', - VALE=(0.0,0.016, - 7200.0,0.016,), - PROL_DROITE='CONSTANT', - PROL_GAUCHE='CONSTANT',); - if DEFI_CHAR_THER['TEMP_EXT_FLUI']!=None: - temp_int = DEFI_CHAR_THER['TEMP_EXT_FLUI'] - else: - temp_int = DEFI_FONCTION(NOM_PARA='INST', - VALE=(0.0,temp_ini,1.0,temp_ini,11.0,60.0, - 600.0,60.0,610.0,280.0,1800.0,280.0,7200.0,280.0,), - PROL_DROITE='CONSTANT', - PROL_GAUCHE='CONSTANT',); - if DEFI_CHAR_THER['COEF_H_AIR']!=None: - coef_ext = DEFI_CHAR_THER['COEF_H_AIR'] - else: - coef_ext = DEFI_FONCTION(NOM_PARA='INST', - VALE=(0.0,1e-05,7200.0,1e-05,), - PROL_DROITE='CONSTANT', - PROL_GAUCHE='CONSTANT',); - - if DEFI_CHAR_THER['TEMP_EXT_AIR']!=None: - temp_ext = DEFI_CHAR_THER['TEMP_EXT_AIR'] - else: - temp_ext = DEFI_FONCTION(NOM_PARA='INST', - VALE=(0.0,20.0,7200.0,20.0,), - PROL_DROITE='CONSTANT', - PROL_GAUCHE='CONSTANT',); - if DEFI_CHAR_THER['LIST_INST']!=None: - transi1 = DEFI_CHAR_THER['LIST_INST'] - else: - transi1 = DEFI_LIST_REEL(DEBUT=0.0, - INTERVALLE=(_F(JUSQU_A=1.0, - NOMBRE=1,), - _F(JUSQU_A=11.0, - NOMBRE=10,), - _F(JUSQU_A=600.0, - NOMBRE=10,), - _F(JUSQU_A=610.0, - NOMBRE=30,), - _F(JUSQU_A=1800.0, - NOMBRE=30,), - _F(JUSQU_A=7200.0, - NOMBRE=10,),),); - else: - temp_ini = DEFI_CHAR_THER['TEMP_INIT'] - coef_int = DEFI_FONCTION(NOM_PARA='INST', - VALE=(0.0,0.016, - 7200.0,0.016,), - PROL_DROITE='CONSTANT', - PROL_GAUCHE='CONSTANT',); - temp_int = DEFI_FONCTION(NOM_PARA='INST', - VALE=(0.0,temp_ini,1.0,temp_ini,11.0,60.0, - 600.0,60.0,610.0,280.0,1800.0,280.0,7200.0,280.0,), - PROL_DROITE='CONSTANT', - PROL_GAUCHE='CONSTANT',); - coef_ext = DEFI_FONCTION(NOM_PARA='INST', - VALE=(0.0,1e-05,7200.0,1e-05,), - PROL_DROITE='CONSTANT', - PROL_GAUCHE='CONSTANT',); - temp_ext = DEFI_FONCTION(NOM_PARA='INST', - VALE=(0.0,20.0,7200.0,20.0,), - PROL_DROITE='CONSTANT', - PROL_GAUCHE='CONSTANT',); - transi1 = DEFI_LIST_REEL(DEBUT=0.0, - INTERVALLE=(_F(JUSQU_A=1.0, - NOMBRE=1,), - _F(JUSQU_A=11.0, - NOMBRE=10,), - _F(JUSQU_A=600.0, - NOMBRE=10,), - _F(JUSQU_A=610.0, - NOMBRE=30,), - _F(JUSQU_A=1800.0, - NOMBRE=30,), - _F(JUSQU_A=7200.0, - NOMBRE=10,),),); - # Que sauver ? - if CHAR_THER != None: - for m in CHAR_THER: - if m['TYPE']=="BRIDE_FLUIDE": - self.DeclareOut('cl_th1',m['CHARGE']) - if m['TYPE']=="BRIDE_AIR": - self.DeclareOut('cl_th2',m['CHARGE']) - if m['TYPE']=="ECROU_GOUJON": - self.DeclareOut('cl_th3',m['CHARGE']) - if m['TYPE']=="BRIDE_JOINT": - self.DeclareOut('cl_th4',m['CHARGE']) - - # Echanges thermiques internes entre le fluide et la bride - cl_th1=AFFE_CHAR_THER_F(MODELE=modther, - ECHANGE=_F(GROUP_MA = 'M_INT', - COEF_H = coef_int, - TEMP_EXT = temp_int,),); - - # Echanges thermiques externes entre bride et air ambiant - cl_th2=AFFE_CHAR_THER_F(MODELE=modther, - ECHANGE=_F(GROUP_MA='M_EXT', - COEF_H=coef_ext, - TEMP_EXT=temp_ext,),); - - # Echanges thermiques entre ecrou et goujon - cl_th3=AFFE_CHAR_THER(MODELE=modther, - LIAISON_GROUP=_F(GROUP_NO_1='N_SCEG', - GROUP_NO_2='N_SCGE', - DDL_1='TEMP', - COEF_MULT_1=1.0, - DDL_2='TEMP', - COEF_MULT_2=-1.0, - COEF_IMPO=0.0,),); - - # Echanges thermiques entre bride et joint - cl_th4=AFFE_CHAR_THER(MODELE=modther, - LIAISON_GROUP=_F(GROUP_NO_1='N_SCBJ', - GROUP_NO_2='N_SCJB', - DDL_1='TEMP', - COEF_MULT_1=1.0, - DDL_2='TEMP', - COEF_MULT_2=-1.0, - COEF_IMPO=0.0,),); - - - - ################################################################# - ########## CALCUL THERMIQUE - ################################################################# - if RESU_THER != None: - self.DeclareOut('resuther',RESU_THER) - - resuther=THER_LINEAIRE(MODELE=modther, - CHAM_MATER=__cham, - EXCIT=(_F(CHARGE=cl_th1,), - _F(CHARGE=cl_th2,), - _F(CHARGE=cl_th3,), - _F(CHARGE=cl_th4,),), - INCREMENT=_F(LIST_INST=transi1,), - ETAT_INIT=_F(VALE=temp_ini,), - TITRE='CABRI THERMIQUE &DATE &HEURE',); - - # Affectation des materiaux (mécanique) - if CHAM_MATER != None: - self.DeclareOut('_chamt',CHAM_MATER) - motscles={} - motscles['AFFE']=[] - motscles['AFFE_VARC']=[] - for mat in affemateriau: - if mat['TOUT'] == None: - # Creation de mots-cles pour les AFFE_CHAR_MECA - motscles['AFFE'].append(_F(GROUP_MA=mat['GROUP_MA'], - MATER = mat['MATER'],) ) - motscles['AFFE_VARC'].append(_F(NOM_VARC='TEMP',GROUP_MA=mat['GROUP_MA'], - EVOL=resuther,NOM_CHAM='TEMP', - VALE_REF = mat['TEMP_REF'],)) - else: - # Creation de mots-cles pour les AFFE_CHAR_MECA - motscles['AFFE'].append(_F(TOUT='OUI', - MATER = mat['MATER']) ) - motscles['AFFE_VARC'].append(_F(NOM_VARC='TEMP',TOUT='OUI', - EVOL=resuther,NOM_CHAM='TEMP', - VALE_REF = mat['TEMP_REF'],)) - - _chamt = AFFE_MATERIAU(MAILLAGE=mail, - MODELE=modther, - AFFE=motscles['AFFE'], - AFFE_VARC=motscles['AFFE_VARC'], - ) - - ################################################################# - ########## CONDITIONS AUX LIMITES MECANIQUES - ################################################################# - # Recuperation des parametres mecaniques - if DEFI_CHAR_MECA != None: - if DEFI_CHAR_MECA['PRETENS']!=None: - f_pret = DEFI_CHAR_MECA['PRETENS'] - else: - f_pret=DEFI_FONCTION(NOM_PARA='INST', - VALE=(0.0,0.0,1.0,-0.02,), - PROL_DROITE='CONSTANT', - PROL_GAUCHE='CONSTANT',); - if DEFI_CHAR_MECA['PRES_REP']!=None: - pre_int = DEFI_CHAR_MECA['PRES_REP'] - else: - pre_int = DEFI_FONCTION(NOM_PARA='INST', - VALE=(0.0,0.0,1.0,0.0,11.0,16.0,), - PROL_DROITE='CONSTANT', - PROL_GAUCHE='CONSTANT',); - if DEFI_CHAR_MECA['EFFE_FOND']!=None: - eff_fond = DEFI_CHAR_MECA['EFFE_FOND'] - else: - eff_fond=DEFI_FONCTION(NOM_PARA='INST', - VALE=(0.0,-0.0,1.0,-0.0,11.0,-20.607059,), - PROL_DROITE='CONSTANT', - PROL_GAUCHE='CONSTANT',); - else: - f_pret=DEFI_FONCTION(NOM_PARA='INST', - VALE=(0.0,0.0,1.0,-0.02,), - PROL_DROITE='CONSTANT', - PROL_GAUCHE='CONSTANT',); - - pre_int = DEFI_FONCTION(NOM_PARA='INST', - VALE=(0.0,0.0,1.0,0.0,11.0,16.0,), - PROL_DROITE='CONSTANT', - PROL_GAUCHE='CONSTANT',); - - eff_fond=DEFI_FONCTION(NOM_PARA='INST', - VALE=(0.0,-0.0,1.0,-0.0,11.0,-20.607059,), - PROL_DROITE='CONSTANT', - PROL_GAUCHE='CONSTANT',); - # Que sauver ? - if CHAR_MECA != None: - for m in CHAR_MECA: - if m['TYPE']=="BLOC_BAS_GOUJ": - self.DeclareOut('cl_me1',m['CHARGE']) - if m['TYPE']=="BLOC_BAS_JOINT": - self.DeclareOut('cl_me2',m['CHARGE']) - if m['TYPE']=="BLOC_LAT_ALES": - self.DeclareOut('cl_me3',m['CHARGE']) - if m['TYPE']=="BLOC_LAT_NALES": - self.DeclareOut('cl_me4',m['CHARGE']) - if m['TYPE']=="PLAN_TUBE": - self.DeclareOut('cl_me5',m['CHARGE']) - if m['TYPE']=="PRES_FLU": - self.DeclareOut('cl_me6',m['CHARGE']) - if m['TYPE']=="EFFET_FOND": - self.DeclareOut('cl_me7',m['CHARGE']) - if m['TYPE']=="CONT_JOINT": - self.DeclareOut('cl_me8',m['CHARGE']) - if m['TYPE']=="SERR_ECROU_1": - self.DeclareOut('cl_me10',m['CHARGE']) - if m['TYPE']=="SERR_ECROU_2": - self.DeclareOut('cl_me11',m['CHARGE']) - - - # Blocage bas du goujon - cl_me1=AFFE_CHAR_MECA(MODELE=modmeca, - DDL_IMPO=_F(GROUP_NO='N_M_GOU', - DZ=0.0,), - INFO=2,); - # Blocage bas du joint - cl_me2=AFFE_CHAR_MECA(MODELE=modmeca, - DDL_IMPO=_F(GROUP_NO='N_M_JOI', - DZ=0.0,), - INFO=2,); - - # Blocage lateral, face laterale avec alesage - cl_me3=AFFE_CHAR_MECA(MODELE=modmeca, - DDL_IMPO=_F(GROUP_NO='N_M_L_AA', - DY=0.0,), - INFO=2,); - - # Face laterale sans alesage - cl_me4=AFFE_CHAR_MECA(MODELE=modmeca, - FACE_IMPO=_F(GROUP_MA='M_L_SA', - DNOR=0.0,), - INFO=2,); - - # Condition de planeite de la face de coupe du tube - cl_me5=AFFE_CHAR_MECA(MODELE=modmeca, - LIAISON_UNIF=_F(GROUP_MA='M_TUB', - DDL='DZ',), - INFO=2,); - # Pression due au fluide - cl_me6=AFFE_CHAR_MECA_F(MODELE=modmeca, - PRES_REP=_F(GROUP_MA='M_INT', - PRES=pre_int,), - INFO=2,); - - # Effet de fond - cl_me7=AFFE_CHAR_MECA_F(MODELE=modmeca, - PRES_REP=_F(GROUP_MA='M_TUB', - PRES=eff_fond,), - INFO=2,); - - # Contact zone de joint - cl_me8=AFFE_CHAR_MECA(MODELE=modmeca, - CONTACT=_F(GROUP_MA_MAIT='SCBJ', - GROUP_MA_ESCL='SCJB',), - INFO=2,); - - # Serrage ecrou/goujon (pre-tensionnement) - cl_me10=AFFE_CHAR_MECA_F(MODELE=modmeca, - LIAISON_GROUP=_F(GROUP_NO_1='N_SCEG', - GROUP_NO_2='N_SCGE', - DDL_1='DZ', - COEF_MULT_1=1.0, - DDL_2='DZ', - COEF_MULT_2=-1.0, - COEF_IMPO=f_pret,), - INFO=2,); - - cl_me11=AFFE_CHAR_MECA(MODELE=modmeca, - LIAISON_GROUP=_F(GROUP_NO_1='N_SCEG', - GROUP_NO_2='N_SCGE', - DDL_1='DX', - COEF_MULT_1=1.0, - DDL_2='DX', - COEF_MULT_2=-1.0, - COEF_IMPO=0.0,), - INFO=2,); - - - ################################################################# - ########## CALCUL MECANIQUE - ################################################################# - # Options de convergence - solveur=SOLVEUR[0].cree_dict_valeurs(SOLVEUR[0].mc_liste) - - # Elimination des valeurs "None" - for i in solveur.keys(): - if solveur[i]==None : del solveur[i] - - - transi2 = DEFI_LIST_REEL(DEBUT=0.0, - INTERVALLE=(_F(JUSQU_A=1.0, - NOMBRE=2,), - _F(JUSQU_A=11.0, - NOMBRE=20,), - _F(JUSQU_A=600.0, - NOMBRE=20,), - _F(JUSQU_A=610.0, - NOMBRE=20,), - _F(JUSQU_A=1800.0, - NOMBRE=20,), - _F(JUSQU_A=7200.0, - NOMBRE=20,),),); - - # Options d'incrementation - if INCREMENT != None: - if INCREMENT['LIST_INST'] != None: - listinst = INCREMENT['LIST_INST'] - else: - listinst = transi2 - - increment=INCREMENT[0].cree_dict_valeurs(INCREMENT[0].mc_liste) - - # Elimination des valeurs "None" - for i in increment.keys(): - if increment[i]==None : del increment[i] - - increment['LIST_INST'] = listinst - - else: - listinst = transi2 - increment =_F( - LIST_INST = listinst, - ), - - # Options de Newton - newton=NEWTON[0].cree_dict_valeurs(NEWTON[0].mc_liste) - # Elimination des valeurs "None" - for i in newton.keys(): - if newton[i]==None : del newton[i] - - # Options de convergence - convergence=CONVERGENCE[0].cree_dict_valeurs(CONVERGENCE[0].mc_liste) - # Elimination des valeurs "None" - for i in convergence.keys(): - if convergence[i]==None : del convergence[i] - - # Options de comportement - # Type incremental (=1) ou elastique (=0) - comp_incr = 0 - if RELATION: - relation=RELATION - if relation == 'VMIS_ISOT_TRAC': - comp_incr = 1 - else: - comp_incr = 0 - else: - relation = 'ELAS' - comp_incr = 0 - - - # Parametres du calcul - if comp_incr == 1: - resumeca=STAT_NON_LINE(MODELE=modmeca, - CHAM_MATER=_chamt, - EXCIT=(_F(CHARGE=cl_me1,), - _F(CHARGE=cl_me2,), - _F(CHARGE=cl_me3,), - _F(CHARGE=cl_me4,), - _F(CHARGE=cl_me5,), - _F(CHARGE=cl_me6,), - _F(CHARGE=cl_me7,), - _F(CHARGE=cl_me8,), - _F(CHARGE=cl_me10,), - _F(CHARGE=cl_me11,), - ), - SOLVEUR = solveur, - COMP_INCR =_F(RELATION=relation,RESO_INTE=resointe), - NEWTON = newton, - INCREMENT = increment, - CONVERGENCE = convergence, - TITRE='CABRI THERMOM\xe9CANIQUE &DATE &HEURE',); - else: - resumeca=STAT_NON_LINE(MODELE=modmeca, - CHAM_MATER=_chamt, - EXCIT=(_F(CHARGE=cl_me1,), - _F(CHARGE=cl_me2,), - _F(CHARGE=cl_me3,), - _F(CHARGE=cl_me4,), - _F(CHARGE=cl_me5,), - _F(CHARGE=cl_me6,), - _F(CHARGE=cl_me7,), - _F(CHARGE=cl_me8,), - _F(CHARGE=cl_me10,), - _F(CHARGE=cl_me11,), - ), - SOLVEUR = solveur, - COMP_ELAS =_F(RELATION=relation,RESO_INTE=resointe), - NEWTON = newton, - INCREMENT = increment, - CONVERGENCE = convergence, - TITRE='CABRI THERMOM\xe9CANIQUE &DATE &HEURE',); - - return ier diff --git a/Aster/Cata/cataSTA9/Intranet/macr_cabri_mail_cata.py b/Aster/Cata/cataSTA9/Intranet/macr_cabri_mail_cata.py deleted file mode 100644 index 6af1e04c..00000000 --- a/Aster/Cata/cataSTA9/Intranet/macr_cabri_mail_cata.py +++ /dev/null @@ -1,92 +0,0 @@ -#@ MODIF macr_cabri_mail_cata Intranet DATE 28/01/2008 AUTEUR PELLET J.PELLET -# -*- coding: iso-8859-1 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2008 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# ====================================================================== - -from Intranet.macr_cabri_mail_ops import macr_cabri_mail_ops -from Cata.cata import * - -MACR_CABRI_MAIL=MACRO(nom="MACR_CABRI_MAIL", - op=macr_cabri_mail_ops, - sd_prod=maillage_sdaster, - fr="maillage d'une jonction boulonnée de tuyauterie", - reentrant='n', - UIinfo={"groupes":("Outils métier",)}, - EXEC_MAILLAGE = FACT(statut='o', - LOGICIEL = SIMP(statut = 'o',typ='TXM',into=("GIBI2000",),), - UNITE_DATG = SIMP(statut = 'f',typ='I',defaut=70,), - UNITE_MGIB = SIMP(statut = 'f',typ='I',defaut=19,), - NIVE_GIBI = SIMP(statut = 'f',typ='I',defaut=10, - into = (3,4,5,6,7,8,9,10,11), - ), - ), - RAFF_MAILLAGE = FACT(statut = 'd', - NB_RADIAL = SIMP(statut = 'f',typ='I',defaut=2,), - NB_CIRCONF = SIMP(statut = 'f',typ='I',defaut=3,), - NB_VERTICAL = SIMP(statut = 'f',typ='I',defaut=6,), - NB_ALESAGE = SIMP(statut = 'f',typ='I',defaut=5,), - ), - VERI_MAIL = FACT(statut='d', - VERIF = SIMP(statut='f',typ='TXM',defaut="OUI",into=("OUI","NON") ), - APLAT = SIMP(statut='f',typ='R',defaut= 1.0E-3 ), - ), - GEOM_BRID = FACT(statut = 'o', - NORME = SIMP(statut = 'o',typ='TXM',into=("OUI","NON"),), - b_bride_iso = BLOC(condition = "NORME == 'OUI'", - TYPE = SIMP(statut='o',typ='TXM', - into=('A','AA','B','B1','C','D','D1','E','F', - 'FF','G','GG','H','H1','I','J','J1', - 'K','L','L1','M','N','O','P','S','T','W'), - ), - ), - b_bride_niso = BLOC(condition = "NORME == 'NON'", - TUBU_D_EXT = SIMP(statut='o',typ='R',), - TUBU_H = SIMP(statut='o',typ='R',), - BRID_D_EXT = SIMP(statut='o',typ='R',), - BRID_D_INT = SIMP(statut='o',typ='R',), - BRID_H = SIMP(statut='o',typ='R',), - BRID_D_CONGE = SIMP(statut='o',typ='R',), - BRID_R_CONGE = SIMP(statut='o',typ='R',), - BRID_D_EPAUL = SIMP(statut='o',typ='R',), - BRID_H_EPAUL = SIMP(statut='o',typ='R',), - BRID_D_ALESAG = SIMP(statut='o',typ='R',), - BRID_P_ALESAG = SIMP(statut='o',typ='R',), - BRID_H_ALESAG = SIMP(statut='o',typ='R',), - GOUJ_N_GOUJON = SIMP(statut='o',typ='I',), - GOUJ_D_GOUJON = SIMP(statut='o',typ='R',), - GOUJ_E_FILET = SIMP(statut='o',typ='R',), - GOUJ_D_RONDEL = SIMP(statut='o',typ='R',), - GOUJ_E_RONDEL = SIMP(statut='o',typ='R',), - GOUJ_D_ECROU = SIMP(statut='o',typ='R',), - GOUJ_E_ECROU = SIMP(statut='o',typ='R',), - ETAN_E_JOINT = SIMP(statut='o',typ='R',), - ), - ), - IMPRESSION = FACT(statut='d', - UNITE = SIMP(statut='f',typ='I'), - FORMAT = SIMP(statut='f',typ='TXM',defaut="ASTER", - into=("ASTER","CASTEM","IDEAS"), - ), - b_impr_castem = BLOC(condition = "FORMAT == 'CASTEM'", - NIVE_GIBI = SIMP(statut='f',typ='I',defaut=10,into=(3,10),), - ), - b_impr_ideas = BLOC(condition = "FORMAT == 'IDEAS'", - VERSION = SIMP(statut='f',typ='I',defaut=5,into=(4,5),), - ), - ), - ); diff --git a/Aster/Cata/cataSTA9/Intranet/macr_cabri_mail_dat.py b/Aster/Cata/cataSTA9/Intranet/macr_cabri_mail_dat.py deleted file mode 100644 index 751f4165..00000000 --- a/Aster/Cata/cataSTA9/Intranet/macr_cabri_mail_dat.py +++ /dev/null @@ -1,628 +0,0 @@ -#@ MODIF macr_cabri_mail_dat Intranet DATE 28/01/2008 AUTEUR PELLET J.PELLET -# -*- coding: iso-8859-1 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2008 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# ====================================================================== - -# Données pour les brides standards - - - -# Pour ajouter une bride x: -# Définir un dico_bride_x comme ci-dessous puis ajoutez-le à dico_bride_std - -# dictionnaire pour la description des variables -dico_var_geo = {'nbgouj':'Nombre de goujons de la jonction boulonnée (GOUJ_N_GOUJON)', - 'dint':'Diamètre intérieur de la bride (BRID_D_INT)', - 'dex1':'Diamétre extérieur de la conduite (TUBU_D_EXT)', - 'dex2':'Position (diamètre) du congé de la bride (BRID_D_CONGE)', - 'dex3':'Diamètre de l''épaulement de la bride au niveau de l''interface d''étanchéité (BRID_D_EPAUL)', - 'dtrou':'Position des alésages de la bride permettant l''introduction des goujons (BRID_P_ALESAG)', - 'dext':'Diamètre extérieur de la bride (BRID_D_EXT)', - 'dt':'Diamètre des alésages de la bride permettant l''introduction des goujons (BRID_D_ALESAG)', - 'drd':'Diamètre de la rondelle (GOUJ_D_RONDEL)', - 'dg':'Diamètre des goujons de la jonction boulonnée (GOUJ_D_GOUJON)', - 'dec':'Diamètre de l''écrou (GOUJ_D_ECROU)', - 'rcong':'Rayon du congé de la bride (BRID_R_CONGE)', - 'he':'Epaisseur de la rondelle (GOUJ_E_RONDEL)', - 'e':'Epaisseur de l''écrou (GOUJ_E_ECROU)', - 'hc1':'Hauteur de la bride (BRID_H)', - 'hcg1':'Hauteur de conduite (TUBU_H)', - 'hb':'Hauteur de l''épaulement de la bride au niveau de l''interface d''étanchéité (BRID_H_EPAUL)', - 'htrou':'Hauteur des alésages de la bride permettant l''introduction des goujons (BRID_H_ALESAG)', - 'pf':'Profondeur (épaisseur) des filets des goujons (GOUJ_E_FILET)', - 'j':'Epaisseur du joint au niveau de l''interface d''étanchéité (ETAN_E_JOINT)'} - -dico_var_msh = {'nrad':'Nombre d''éléments radiaux (NBR_RAD)', - 'ncir':'Nombre d''éléments circonférentiels (NBR_CIR)', - 'nver':'Nombre d''éléments verticaux (NBR_VER)', - 'nsect':'Nombre d''éléments de l''alésage (NBR_ALE)', - 'temps':'Temps d''analyse'} - -# dictionnaires des brides standards -dico_bride_A = {'nbgouj': 4, - 'dint': 15.76, - 'dex1': 21.3, - 'dex2': 38., - 'dex3': 48., - 'dtrou': 67., - 'dext': 95., - 'dt': 14., - 'drd': 25., - 'dg': 12., - 'dec': 18., - 'rcong': 3., - 'he': 12., - 'e': 2.5, - 'hc1': 46.5, - 'hcg1': 20, - 'hb': 1.5, - 'htrou': 20., - 'pf': 1.5, - 'j': 2} - -dico_bride_AA = {'nbgouj': 32, - 'dint': 336.5, - 'dex1': 355.6, - 'dex2': 395., - 'dex3': 415., - 'dtrou': 460., - 'dext': 515., - 'dt': 22., - 'drd': 36., - 'dg': 20., - 'dec': 30., - 'rcong': 5., - 'he': 20., - 'e': 3., - 'hc1': 115., - 'hcg1': 115./2., - 'hb': 3., - 'htrou': 47., - 'pf': 2.2, - 'j': 2} - -dico_bride_B = {'nbgouj': 4, - 'dint': 26.64, - 'dex1': 33.4, - 'dex2': 53., - 'dex3': 63., - 'dtrou': 88., - 'dext': 123., - 'dt': 16., - 'drd': 27., - 'dg': 14., - 'dec': 21., - 'rcong': 4., - 'he': 14., - 'e': 2.5, - 'hc1': 59., - 'hcg1': 59./2., - 'hb': 1.5, - 'htrou': 27.5, - 'pf': 1.7, - 'j': 2} -dico_bride_B1 = {'nbgouj': 4, - 'dint': 24.3, - 'dex1': 33.4, - 'dex2': 53., - 'dex3': 63., - 'dtrou': 88., - 'dext': 123., - 'dt': 16., - 'drd': 27., - 'dg': 14., - 'dec': 21., - 'rcong': 4., - 'he': 14., - 'e': 2.5, - 'hc1': 59., - 'hcg1': 59./2., - 'hb': 1.5, - 'htrou': 27.5, - 'pf': 1.7, - 'j': 2} -dico_bride_C = {'nbgouj': 8, - 'dint': 52.48, - 'dex1': 60.3, - 'dex2': 84., - 'dex3': 100., - 'dtrou': 127., - 'dext': 165., - 'dt': 18., - 'drd': 30, - 'dg': 16., - 'dec': 24., - 'rcong': 4., - 'he': 16., - 'e': 3, - 'hc1': 70., - 'hcg1': 70./2., - 'hb': 1.5, - 'htrou': 21., - 'pf': 1.7, - 'j': 2} -dico_bride_D = {'nbgouj': 8, - 'dint': 42.9, - 'dex1': 60.3, - 'dex2': 84., - 'dex3': 100., - 'dtrou': 127., - 'dext': 165., - 'dt': 18., - 'drd': 30, - 'dg': 16., - 'dec': 24., - 'rcong': 5., - 'he': 16., - 'e': 3., - 'hc1': 87.6, - 'hcg1': 87.6/2., - 'hb': 1.5, - 'htrou': 38.5, - 'pf': 1.7, - 'j': 2} -dico_bride_D1 = {'nbgouj': 8, - 'dint': 49.22, - 'dex1': 60.3, - 'dex2': 84., - 'dex3': 100., - 'dtrou': 127., - 'dext': 165., - 'dt': 18., - 'drd': 30, - 'dg': 16., - 'dec': 24., - 'rcong': 5., - 'he': 16., - 'e': 3., - 'hc1': 87.6, - 'hcg1': 87.6/2., - 'hb': 1.5, - 'htrou': 38.5, - 'pf': 1.7, - 'j': 2} -dico_bride_E = {'nbgouj': 8, - 'dint': 83.1, - 'dex1': 88.9, - 'dex2': 117.5, - 'dex3': 135., - 'dtrou': 165., - 'dext': 209., - 'dt': 18., - 'drd': 30., - 'dg': 16., - 'dec': 24., - 'rcong': 5., - 'he': 16., - 'e': 3., - 'hc1': 80., - 'hcg1': 80./2., - 'hb': 2., - 'htrou': 27., - 'pf': 1.7, - 'j': 2} -dico_bride_F = {'nbgouj': 8, - 'dint': 73.66, - 'dex1': 88.9, - 'dex2': 117.5, - 'dex3': 135., - 'dtrou': 165., - 'dext': 209., - 'dt': 18., - 'drd': 30., - 'dg': 16., - 'dec': 24., - 'rcong': 5., - 'he': 16., - 'e': 3., - 'hc1': 89., - 'hcg1': 89./2., - 'hb': 2., - 'htrou': 36., - 'pf': 1.7, - 'j': 2} -dico_bride_FF = {'nbgouj': 32, - 'dint': 396.99, - 'dex1': 406.4, - 'dex2': 440., - 'dex3': 455., - 'dtrou': 485., - 'dext': 535., - 'dt': 18., - 'drd': 30., - 'dg': 16., - 'dec': 24., - 'rcong': 5., - 'he': 16., - 'e': 3., - 'hc1': 99., - 'hcg1': 99./2., - 'hb': 3., - 'htrou': 40., - 'pf': 1.7, - 'j': 2} -dico_bride_G = {'nbgouj': 12, - 'dint': 66.7, - 'dex1': 88.9, - 'dex2': 117.5, - 'dex3': 135., - 'dtrou': 165., - 'dext': 209., - 'dt': 18., - 'drd': 30., - 'dg': 16., - 'dec': 24., - 'rcong': 5., - 'he': 16., - 'e': 3., - 'hc1': 98., - 'hcg1': 98./2., - 'hb': 2., - 'htrou': 45., - 'pf': 1.7, - 'j': 2} -dico_bride_GG = {'nbgouj': 36, - 'dint': 381., - 'dex1': 406.4, - 'dex2': 445., - 'dex3': 460., - 'dtrou': 495., - 'dext': 545., - 'dt': 22., - 'drd': 36, - 'dg': 20., - 'dec': 30., - 'rcong': 5., - 'he': 20., - 'e': 3., - 'hc1': 129., - 'hcg1': 129./2., - 'hb': 3., - 'htrou': 63., - 'pf': 2.2, - 'j': 2} -dico_bride_H = {'nbgouj': 12, - 'dint': 108.2, - 'dex1': 114.3, - 'dex2': 146., - 'dex3': 157., - 'dtrou': 190., - 'dext': 225., - 'dt': 18., - 'drd': 30., - 'dg': 16., - 'dec': 24., - 'rcong': 5., - 'he': 16., - 'e': 3., - 'hc1': 89., - 'hcg1': 89./2., - 'hb': 2., - 'htrou': 33., - 'pf': 1.7, - 'j': 2} -dico_bride_H1 = {'nbgouj': 12, - 'dint': 102.6, - 'dex1': 114.3, - 'dex2': 146., - 'dex3': 157., - 'dtrou': 190., - 'dext': 225., - 'dt': 18., - 'drd': 30., - 'dg': 16., - 'dec': 24., - 'rcong': 5., - 'he': 16., - 'e': 3., - 'hc1': 89., - 'hcg1': 89./2., - 'hb': 2., - 'htrou': 33., - 'pf': 1.7, - 'j': 2} -dico_bride_I = {'nbgouj': 18, - 'dint': 92.1, - 'dex1': 114.3, - 'dex2': 146., - 'dex3': 160., - 'dtrou': 200., - 'dext': 255., - 'dt': 20., - 'drd': 32., - 'dg': 18., - 'dec': 27., - 'rcong': 5., - 'he': 18., - 'e': 3., - 'hc1': 99., - 'hcg1': 99./2., - 'hb': 2., - 'htrou': 43., - 'pf': 2.2, - 'j': 2} -dico_bride_J = {'nbgouj': 18, - 'dint': 87.34, - 'dex1': 114.3, - 'dex2': 146., - 'dex3': 160., - 'dtrou': 200., - 'dext': 255., - 'dt': 20., - 'drd': 32., - 'dg': 18., - 'dec': 27., - 'rcong': 5., - 'he': 18., - 'e': 3., - 'hc1': 111., - 'hcg1': 111./2., - 'hb': 2., - 'htrou': 55., - 'pf': 2.2, - 'j': 2} -dico_bride_J1 = {'nbgouj': 18, - 'dint': 87.3, - 'dex1': 114.3, - 'dex2': 146., - 'dex3': 160., - 'dtrou': 200., - 'dext': 255., - 'dt': 22., - 'drd': 36., - 'dg': 20., - 'dec': 30., - 'rcong': 5., - 'he': 20., - 'e': 3., - 'hc1': 111., - 'hcg1': 111./2., - 'hb': 2., - 'htrou': 55., - 'pf': 2.2, - 'j': 2} -dico_bride_K = {'nbgouj': 8, - 'dint': 161.5, - 'dex1': 168.3, - 'dex2': 192., - 'dex3': 210., - 'dtrou': 235., - 'dext': 280., - 'dt': 18., - 'drd': 30., - 'dg': 16., - 'dec': 24., - 'rcong': 5., - 'he': 16., - 'e': 3., - 'hc1': 84., - 'hcg1': 84./2., - 'hb': 2., - 'htrou': 28., - 'pf': 1.7, - 'j': 2} -dico_bride_L = {'nbgouj': 16, - 'dint': 154.8, - 'dex1': 168.3, - 'dex2': 206., - 'dex3': 220., - 'dtrou': 255., - 'dext': 317., - 'dt': 18., - 'drd': 30., - 'dg': 16., - 'dec': 24., - 'rcong': 5., - 'he': 16., - 'e': 3., - 'hc1': 96., - 'hcg1': 96./2., - 'hb': 2., - 'htrou': 40., - 'pf': 1.7, - 'j': 2} -dico_bride_L1 = {'nbgouj': 16, - 'dint': 154.8, - 'dex1': 168.3, - 'dex2': 206., - 'dex3': 220., - 'dtrou': 255., - 'dext': 317., - 'dt': 20., - 'drd': 32., - 'dg': 18., - 'dec': 27., - 'rcong': 5., - 'he': 18., - 'e': 3., - 'hc1': 96., - 'hcg1': 96./2., - 'hb': 2., - 'htrou': 40., - 'pf': 2.2, - 'j': 2} -dico_bride_M = {'nbgouj': 16, - 'dint': 139.7, - 'dex1': 168.3, - 'dex2': 206., - 'dex3': 220., - 'dtrou': 250., - 'dext': 290., - 'dt': 24., - 'drd': 40., - 'dg': 22., - 'dec': 32., - 'rcong': 5., - 'he': 22., - 'e': 3., - 'hc1': 135., - 'hcg1': 135./2., - 'hb': 3., - 'htrou': 62., - 'pf': 2.2, - 'j': 2} -dico_bride_N = {'nbgouj': 12, - 'dint': 131.9, - 'dex1': 168.3, - 'dex2': 220., - 'dex3': 240., - 'dtrou': 290., - 'dext': 365., - 'dt': 30., - 'drd': 48., - 'dg': 27., - 'dec': 41., - 'rcong': 5., - 'he': 27., - 'e': 4., - 'hc1': 148., - 'hcg1': 148./2., - 'hb': 3., - 'htrou': 75., - 'pf': 2.6, - 'j': 2} -dico_bride_O = {'nbgouj': 12, - 'dint': 211.58, - 'dex1': 219.1, - 'dex2': 248., - 'dex3': 260., - 'dtrou': 292., - 'dext': 335., - 'dt': 20., - 'drd': 32., - 'dg': 18., - 'dec': 27., - 'rcong': 5., - 'he': 18., - 'e': 3., - 'hc1': 87., - 'hcg1': 87./2., - 'hb': 3., - 'htrou': 30., - 'pf': 2.2, - 'j': 2} -dico_bride_P = {'nbgouj': 16, - 'dint': 202.74, - 'dex1': 219.1, - 'dex2': 248., - 'dex3': 260., - 'dtrou': 292., - 'dext': 335., - 'dt': 20., - 'drd': 32, - 'dg': 18., - 'dec': 27., - 'rcong': 5., - 'he': 18., - 'e': 3., - 'hc1': 99., - 'hcg1': 99./2., - 'hb': 3., - 'htrou': 42., - 'pf': 2.2, - 'j': 2} -dico_bride_S = {'nbgouj': 16, - 'dint': 264.62, - 'dex1': 273., - 'dex2': 305., - 'dex3': 315., - 'dtrou': 350., - 'dext': 390., - 'dt': 18., - 'drd': 30., - 'dg': 16., - 'dec': 24., - 'rcong': 5., - 'he': 16., - 'e': 3., - 'hc1': 89., - 'hcg1': 89./2., - 'hb': 3., - 'htrou': 32., - 'pf': 1.7, - 'j': 2} -dico_bride_T = {'nbgouj': 16, - 'dint': 254.56, - 'dex1': 273., - 'dex2': 320., - 'dex3': 340., - 'dtrou': 385., - 'dext': 444., - 'dt': 27., - 'drd': 45., - 'dg': 24., - 'dec': 36., - 'rcong': 5., - 'he': 24., - 'e': 4., - 'hc1': 128., - 'hcg1': 128./2., - 'hb': 3., - 'htrou': 55., - 'pf': 2.6, - 'j': 2} -dico_bride_W = {'nbgouj': 28, - 'dint': 314.76, - 'dex1': 323.9, - 'dex2': 360., - 'dex3': 385., - 'dtrou': 415., - 'dext': 460., - 'dt': 18., - 'drd': 30., - 'dg': 16., - 'dec': 24., - 'rcong': 5., - 'he': 16., - 'e': 3., - 'hc1': 96., - 'hcg1': 96./2., - 'hb': 3., - 'htrou': 37., - 'pf': 1.7, - 'j': 2} - - -# dictionnaire pour faire le lien entre l'option de bride et les valeurs normalisées -dico_bride_std = {'AA':dico_bride_AA, - 'A':dico_bride_A, - 'B':dico_bride_B, - 'B1':dico_bride_B1, - 'C':dico_bride_C, - 'D':dico_bride_D, - 'D1':dico_bride_D1, - 'E':dico_bride_E, - 'F':dico_bride_F, - 'FF':dico_bride_FF, - 'G':dico_bride_G, - 'GG':dico_bride_GG, - 'H':dico_bride_H, - 'H1':dico_bride_H1, - 'I':dico_bride_I, - 'J':dico_bride_J, - 'J1':dico_bride_J1, - 'K':dico_bride_K, - 'L':dico_bride_L, - 'L1':dico_bride_L1, - 'M':dico_bride_M, - 'N':dico_bride_N, - 'O':dico_bride_O, - 'P':dico_bride_P, - 'S':dico_bride_S, - 'T':dico_bride_T, - 'W':dico_bride_W} diff --git a/Aster/Cata/cataSTA9/Intranet/macr_cabri_mail_ops.py b/Aster/Cata/cataSTA9/Intranet/macr_cabri_mail_ops.py deleted file mode 100644 index f122a995..00000000 --- a/Aster/Cata/cataSTA9/Intranet/macr_cabri_mail_ops.py +++ /dev/null @@ -1,459 +0,0 @@ -#@ MODIF macr_cabri_mail_ops Intranet DATE 28/01/2008 AUTEUR PELLET J.PELLET -# -*- coding: iso-8859-1 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2008 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# ====================================================================== - -import os - -def macr_cabri_mail_ops(self,EXEC_MAILLAGE,RAFF_MAILLAGE,VERI_MAIL,GEOM_BRID, - IMPRESSION,**args): - """ - Ecriture de la macro MACR_CABRI_MAIL - """ - import types - from Accas import _F - - ier=0 - - # On importe les definitions des commandes a utiliser dans la macro - # Le nom de la variable doit etre obligatoirement le nom de la commande - EXEC_LOGICIEL = self.get_cmd('EXEC_LOGICIEL') - LIRE_MAILLAGE = self.get_cmd('LIRE_MAILLAGE') - PRE_GIBI = self.get_cmd('PRE_GIBI') - IMPR_RESU = self.get_cmd('IMPR_RESU') - - # La macro compte pour 1 dans la numerotation des commandes - self.set_icmd(1) - - # Le concept sortant (de type mail) est nommé 'nomres' dans - # le contexte de la macro - - self.DeclareOut('nomres',self.sd) - - # Chemin de Gibi - import aster - loc_gibi=aster.repout() - gibi2000=loc_gibi+'gibi' - - # Unité pour le fichier maillage produit (format GIBI) - unite_mgib = EXEC_MAILLAGE['UNITE_MGIB'] - # Unité pour le fichier de commandes GIBI - unite_datg = EXEC_MAILLAGE['UNITE_DATG'] - # Niveau gibi - niveau_gibi = EXEC_MAILLAGE['NIVE_GIBI'] - - # Verif mail - ver_apla = VERI_MAIL['APLAT'] - ver_veri = VERI_MAIL['VERIF'] - - # Impression - if IMPRESSION['UNITE']!=None: - imp_unit = IMPRESSION['UNITE'] - imp_unitF = 1 - else: - imp_unitF = 0 - if IMPRESSION['FORMAT']!=None: - imp_form = IMPRESSION['FORMAT'] - imp_formF = 1 - else: - imp_formF = 0 -# if IMPRESSION['FICHIER']!=None: -# imp_fich = IMPRESSION['FICHIER'] -# imp_fichF = 1 -# else: -# imp_fichF = 0 - - # Maillage - nrad = RAFF_MAILLAGE['NB_RADIAL'] - ncir = RAFF_MAILLAGE['NB_CIRCONF'] - nver = RAFF_MAILLAGE['NB_VERTICAL'] - nsect = RAFF_MAILLAGE['NB_ALESAGE'] - temps = 5. - - maillage = {'nrad': nrad, - 'ncir': ncir, - 'nver': nver, - 'nsect': nsect, - 'temps' : temps,} - - # Création du fichier datg - - if GEOM_BRID['NORME'] == 'OUI': - # Bride standard - type_bride = GEOM_BRID['TYPE'] - ### Ecriture du fichier GIBI principal (dgib) - Bride STANDARD - write_file_dgib_STD(unite_mgib,unite_datg,maillage,type_bride) - else: - # Bride quelconque - geo_bride_qqe = {'nbgouj': GEOM_BRID['GOUJ_N_GOUJON'], - 'dint': GEOM_BRID['BRID_D_INT'], - 'dex1': GEOM_BRID['TUBU_D_EXT'], - 'dex2': GEOM_BRID['BRID_D_CONGE'], - 'dex3': GEOM_BRID['BRID_D_EPAUL'], - 'dtrou': GEOM_BRID['BRID_P_ALESAG'], - 'dext': GEOM_BRID['BRID_D_EXT'], - 'dt': GEOM_BRID['BRID_D_ALESAG'], - 'drd': GEOM_BRID['GOUJ_D_RONDEL'], - 'dg': GEOM_BRID['GOUJ_D_GOUJON'], - 'dec': GEOM_BRID['GOUJ_D_ECROU'], - 'rcong': GEOM_BRID['BRID_R_CONGE'], - 'he': GEOM_BRID['GOUJ_E_ECROU'], - 'e': GEOM_BRID['GOUJ_E_RONDEL'], - 'hc1': GEOM_BRID['BRID_H'], - 'hcg1': GEOM_BRID['TUBU_H'], - 'hb': GEOM_BRID['BRID_H_EPAUL'], - 'htrou': GEOM_BRID['BRID_H_ALESAG'], - 'pf': GEOM_BRID['GOUJ_E_FILET'], - 'j': GEOM_BRID['ETAN_E_JOINT']} - ### Ecriture du fichier GIBI principal (dgib) - Bride QUELCONQUE - write_file_dgib_QQE(unite_mgib,unite_datg,maillage,geo_bride_qqe) - - fichier_datg = 'fort.'+str(unite_datg) - fichier_mgib = 'fort.'+str(unite_mgib) - - # Lancement de GIBI - EXEC_LOGICIEL( - LOGICIEL=gibi2000, - ARGUMENT=(fichier_datg, fichier_mgib), - ) - # Lecture du maillage GIBI dans ASTER - PRE_GIBI( - UNITE_GIBI = unite_mgib, - ) - - nomres = LIRE_MAILLAGE(VERI_MAIL=_F(APLAT = ver_apla, - VERIF = ver_veri ),) - -# if (imp_fichF == 1): -# print imp_fich - if (imp_formF == 1): - print imp_form - if (imp_unitF == 1): - print imp_unit - # Impression du fichier maillage - if (imp_formF == 1): - if (imp_form == 'CASTEM'): - imp_ngib = IMPRESSION['NIVE_GIBI'] - IMPR_RESU( RESU = _F(MAILLAGE=nomres, ), - FORMAT = 'CASTEM', NIVE_GIBI = imp_ngib ) - if (imp_form == 'IDEAS'): - imp_nver = IMPRESSION['VERSION'] - IMPR_RESU(RESU = _F(MAILLAGE=nomres,), - FORMAT = 'IDEAS', VERSION = imp_nver ) - - return ier - - -############################################################################################## -# Liste des fonctions -############################################################################################## - -############# -## EXTERNES (appelables depuis l'extérieur) -############# - -### Ecriture du fichier GIBI principal (dgib) - Bride STANDARD -# null = write_file_dgib_STD(unite_mgib,unite_datg,msh_bride,geo_bride) - -### Ecriture du fichier GIBI principal (dgib) - Bride QUELCONQUE -# null = write_file_dgib_QQE(unite_mgib,unite_datg,msh_bride,geo_bride) - -### Imprime tout le catalogue des brides standards disponibles dans un fichier texte -# null = print_bride_std(nom_fichier) - -### Catalogue complet des brides standards disponibles -# txt = bride_std() - -############# -## INTERNES (réservées au travail interne) -############# - -### Génération du nom du fichier pour le fichier maillage résultant (format GIBI) -# NomFichier(txt) = name_file_mgib(unite_mgib): - -### Génération du nom du fichier pour le fichier générant le maillage (commandes GIBI) -# NomFichier(txt) = name_file_datg(unite_datg): - -### Récupère un fichier texte DATG -# Txt = text_datg(fichier_datg): - -### Génération du texte pour les variables -# Txt = para_text(dico_var,var): - - - -#============================================================================================= -# Importation des modules Python -#============================================================================================= - -from Intranet.macr_cabri_mail_dat import dico_var_geo,dico_var_msh,dico_bride_std - -#============================================================================================= -# Fonctions principales -#============================================================================================= -# Ecriture du fichier GIBI principal (dgib) - Bride STANDARD -def write_file_dgib_STD(unite_mgib,unite_datg,msh_bride,geo_bride): - - # Nom du fichier maillage produit par GIBI - nomFichierMGIB = name_file_mgib(unite_mgib) - - # Nom du fichier de commandes pour GIBI - nomFichierDATG = name_file_datg(unite_datg) - - # Ouverture du fichier d'entrée de commandes - fdgib=open(nomFichierDATG,'w') - - # En-tete - text = "**************************************************************\n" - text = text + "* Fichier GIBI pour le maillage d'une bride \n" - text = text + "**************************************************************\n" - text = text + "\n" - text = text + "* Ce fichier a été généré automatiquement par la macro ASTER MACR_CABRI_MAIL \n" - text = text + "* Ne pas modifier\n" - text = text + "\n" - text = text + "**************************************************************\n" - text = text + "* Type bride: Bride standard \n" - text = text + "**************************************************************\n" - text = text + "titre '"+"Bride standard"+"';\n" - text = text + "** Type bride standard: "+geo_bride+"\n" - - text = text + "\n" - text = text + "nomfich = CHAINE \n" - if len(nomFichierMGIB)>72: - raise Exception, 'Nom de fichier trop long (limité à 72 caractères ' \ - 'pour GIBI) :\n',nomFichierMGIB - elif len(nomFichierMGIB)<=69: - text = text + "'"+nomFichierMGIB+"';\n" - else: - text = text + "'"+nomFichierMGIB[:69]+"'\n" \ - + "'"+nomFichierMGIB[69:]+"';\n" - text = text + "opti dime 3 elem cub8 SAUV FORM nomfich;\n" - text = text + "dens 1;\n" - text = text + "\n" - fdgib.write(text) - - # Procédures internes supplémentaires - text = "**************************************************************\n" - text = text + "* Procédures supplémentaires \n" - text = text + "**************************************************************\n" - text = text + text_datg_pro() - fdgib.write(text) - - # Début de procédure de création du maillage - text = "**************************************************************\n" - text = text + "**************************************************************\n" - text = text + "********* Début de procédure de création du maillage *********\n" - text = text + "**************************************************************\n" - text = text + "**************************************************************\n" - text = text + "\n debproc constru;\n" - fdgib.write(text) - - # Paramètres géométriques - car_bride = dico_bride_std[geo_bride] - text = "**************************************************************\n" - text = text + "* Paramètres géométriques \n" - text = text + "**************************************************************\n" - text = text + para_text(dico_var_geo,car_bride) - fdgib.write(text) - - # Paramètres du maillage - text = "**************************************************************\n" - text = text + "* Paramètres physiques \n" - text = text + "**************************************************************\n" - text = text + para_text(dico_var_msh,msh_bride) - fdgib.write(text) - - # Algorithme du maillage - text = "**************************************************************\n" - text = text + "* Algorithme de maillage \n" - text = text + "**************************************************************\n" - text = text + text_datg_std() - fdgib.write(text) - - # Fermeture du fichier maillage - fdgib.close() - - -# Ecriture du fichier GIBI principal (dgib) - Bride QUELCONQUE -def write_file_dgib_QQE(unite_mgib,unite_datg,msh_bride,geo_bride): - - # Nom du fichier maillage produit par GIBI - nomFichierMGIB = name_file_mgib(unite_mgib) - - # Nom du fichier de commandes pour GIBI - nomFichierDATG = name_file_datg(unite_datg) - - # Ouverture du fichier d'entree de commandes - fdgib=open(nomFichierDATG,'w') - - # En-tete - text = "**************************************************************\n" - text = text + "* Fichier GIBI pour le maillage d'une bride \n" - text = text + "**************************************************************\n" - text = text + "\n" - text = text + "* Ce fichier a été généré automatiquement par la macro ASTER MACR_CABRI_MAIL \n" - text = text + "* Ne pas modifier\n" - text = text + "\n" - text = text + "**************************************************************\n" - text = text + "* Type bride: Bride quelconque\n" - text = text + "**************************************************************\n" - text = text + "titre '"+"Bride Quelconque"+"';\n" - text = text + "\n" - text = text + "nomfich = CHAINE \n" - if len(nomFichierMGIB)>72: - raise Exception, 'Nom de fichier trop long (limité à 72 caractères ' \ - 'pour GIBI) :\n',nomFichierMGIB - elif len(nomFichierMGIB)<=69: - text = text + "'"+nomFichierMGIB+"';\n" - else: - text = text + "'"+nomFichierMGIB[:69]+"'\n" \ - + "'"+nomFichierMGIB[69:]+"';\n" - text = text + "opti dime 3 elem cub8 SAUV FORM nomfich;\n" - text = text + "dens 1;\n" - text = text + "\n" - fdgib.write(text) - - # Procédures internes supplémentaires - text = "**************************************************************\n" - text = text + "* Procédures supplémentaires \n" - text = text + "**************************************************************\n" - text = text + text_datg_pro() - fdgib.write(text) - - # Début de procédure de création du maillage - text = "**************************************************************\n" - text = text + "**************************************************************\n" - text = text + "********* Début de procédure de création du maillage *********\n" - text = text + "**************************************************************\n" - text = text + "**************************************************************\n" - text = text + "\n debproc constru;\n" - fdgib.write(text) - - # Paramètres géométriques - text = "**************************************************************\n" - text = text + "* Paramètres géométriques \n" - text = text + "**************************************************************\n" - text = text + para_text(dico_var_geo,geo_bride) - fdgib.write(text) - - # Paramètres du maillage - text = "**************************************************************\n" - text = text + "* Paramètres physiques \n" - text = text + "**************************************************************\n" - text = text + para_text(dico_var_msh,msh_bride) - fdgib.write(text) - - # Algorithme du maillage - text = "**************************************************************\n" - text = text + "* Algorithme de maillage \n" - text = text + "**************************************************************\n" - text = text + text_datg_qqe() - fdgib.write(text) - - # Fermeture du fichier maillage - fdgib.close() - -# Génération du nom du fichier pour le fichier maillage résultant (format GIBI) -def name_file_mgib(unite_mgib): - cur_dir = os.getcwd() - nomFichier = cur_dir+'/fort.'+str(unite_mgib) - return nomFichier - - -# Génération du nom du fichier pour le fichier générant le maillage (commandes GIBI) -def name_file_datg(unite_datg): - cur_dir = os.getcwd() - nomFichier = cur_dir+'/fort.'+str(unite_datg) - return nomFichier - -# Récupère un fichier texte DATG: texte GIBI pour procédures -def text_datg_pro(): - import aster - loc_datg = aster.repdex() - datg_bridePro = loc_datg+"macr_cabri_mail_proc.datg" - fproc=open(datg_bridePro,'r') - procText = fproc.read() - fproc.close() - - return procText - -# Récupère un fichier texte DATG: texte GIBI pour bride quelconque -def text_datg_qqe(): - import aster - loc_datg = aster.repdex() - datg_brideQqe = loc_datg+"macr_cabri_mail_qqe.datg" - fproc=open(datg_brideQqe,'r') - procText = fproc.read() - fproc.close() - - return procText - -# Récupère un fichier texte DATG: texte GIBI pour bride standard -def text_datg_std(): - import aster - loc_datg = aster.repdex() - datg_brideStd = loc_datg+"macr_cabri_mail_std.datg" - fproc=open(datg_brideStd,'r') - procText = fproc.read() - fproc.close() - - return procText - -# Génération du texte pour les variables -def para_text(dico_var,var): - text = '\n' - for nom_var in var.keys(): - text = text+"* "+dico_var[nom_var]+"\n" - text = text+nom_var+" = "+`var[nom_var]`+";\n" - return text - -#============================================================================================= -# Accès au catalogue des brides standards -# (les brides standards sont décrites dans le fichier Data_Brides.py) -#============================================================================================= - - - -# Imprime tout le catalogue des brides standards disponibles dans un fichier texte -def print_bride_std(nom_fichier): - text = bride_std() - # Ouverture du fichier - finfo=open(nom_fichier,'w') - # Ecriture des infos - finfo.write(text) - # Fermeture du fichier - finfo.close() - -# Catalogue complet des brides standards disponibles -def bride_std(): - # Ligne d'info - text = "Liste des brides standards avec leurs dimensions\n" - # Première ligne - text = text+"\t" - for nom_variable in dico_var_geo.keys(): - text = text + nom_variable+"\t\t" - text = text + "\n" - # Lignes suivantes - for nom_bride in dico_bride_std.keys(): - bride = dico_bride_std[nom_bride] - text = text + nom_bride + '\t' - for nom_var in dico_var_geo.keys(): - chaine = "%f" % (bride[nom_var]) - text = text+chaine+"\t" - text = text + "\n" - return text diff --git a/Aster/Cata/cataSTA9/Intranet/macro_bascule_schema_ops.py b/Aster/Cata/cataSTA9/Intranet/macro_bascule_schema_ops.py deleted file mode 100644 index 8f763edd..00000000 --- a/Aster/Cata/cataSTA9/Intranet/macro_bascule_schema_ops.py +++ /dev/null @@ -1,296 +0,0 @@ -#@ MODIF macro_bascule_schema_ops Intranet DATE 17/12/2007 AUTEUR GREFFET N.GREFFET -# -*- coding: iso-8859-1 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2007 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# ====================================================================== - -def macro_bascule_schema_ops (self,MODE,MATE,CARA, - INCR_I,INCR_E, - SCH_TEMPS_I,SCH_TEMPS_E,SCH_TEMPS_EQ, - C_INCR_I,C_INCR_E, - EXC_T,NEWT,INIT,TP_BAS,SCH_INI,EQUILIBRAGE,**args): - ier=0 - import copy - import aster - import string - import types - from Accas import _F - from Noyau.N_utils import AsType - from Utilitai.Utmess import UTMESS - # On importe les definitions des commandes a utiliser dans la macro - DYNA_NON_LINE =self.get_cmd('DYNA_NON_LINE') - CREA_CHAMP =self.get_cmd('CREA_CHAMP') - DEFI_LIST_REEL =self.get_cmd('DEFI_LIST_REEL') - # La macro compte pour 1 dans la numerotation des commandes - self.set_icmd(1) - # Le concept sortant (de type evol_noli) est nommé - # 'nomres' dans le contexte de la macro - self.DeclareOut('nomres',self.sd) - # - # - dexct=[] - for j in EXC_T : - dexct.append(j.cree_dict_valeurs(j.mc_liste)) - for i in dexct[-1].keys(): - if dexct[-1][i]==None : del dexct[-1][i] - # - dComp_incri=[] - for j in C_INCR_I : - dComp_incri.append(j.cree_dict_valeurs(j.mc_liste)) - for i in dComp_incri[-1].keys(): - if dComp_incri[-1][i]==None : del dComp_incri[-1][i] - # - dComp_incre=[] - for j in C_INCR_E : - dComp_incre.append(j.cree_dict_valeurs(j.mc_liste)) - for i in dComp_incre[-1].keys(): - if dComp_incre[-1][i]==None : del dComp_incre[-1][i] - # - dincri=[] - for j in INCR_I : - dincri.append(j.cree_dict_valeurs(j.mc_liste)) - for i in dincri[-1].keys(): - if dincri[-1][i]==None : del dincri[-1][i] - # - dincre=[] - for j in INCR_E : - dincre.append(j.cree_dict_valeurs(j.mc_liste)) - for i in dincre[-1].keys(): - if dincre[-1][i]==None : del dincre[-1][i] - # - dschi=[] - for j in SCH_TEMPS_I : - dschi.append(j.cree_dict_valeurs(j.mc_liste)) - for i in dschi[-1].keys(): - if dschi[-1][i]==None : del dschi[-1][i] - # - dsche=[] - for j in SCH_TEMPS_I : - dsche.append(j.cree_dict_valeurs(j.mc_liste)) - for i in dsche[-1].keys(): - if dsche[-1][i]==None : del dsche[-1][i] - # - dscheq=[] - for j in SCH_TEMPS_I : - dscheq.append(j.cree_dict_valeurs(j.mc_liste)) - for i in dscheq[-1].keys(): - if dscheq[-1][i]==None : del dscheq[-1][i] - # - dnew=[] - for j in NEWT : - dnew.append(j.cree_dict_valeurs(j.mc_liste)) - for i in dnew[-1].keys(): - if dnew[-1][i]==None : del dnew[-1][i] - # - dini=[] - for j in INIT : - dini.append(j.cree_dict_valeurs(j.mc_liste)) - for i in dini[-1].keys(): - if dini[-1][i]==None : del dini[-1][i] - # - dequi=[] - for j in EQUILIBRAGE : - dequi.append(j.cree_dict_valeurs(j.mc_liste)) - for i in dequi[-1].keys(): - if dequi[-1][i]==None : del dequi[-1][i] - # - __L0 = TP_BAS['VALE'] - dincri1=copy.copy(dincri) - dincri1[-1]['INST_FIN']= __L0[0] - # - __dtimp=dequi[-1]['DT_IMP'] - __dtexp=dequi[-1]['DT_EXP'] - # - __dim=(-1)*len(dComp_incri) - __lis=range(0,__dim,-1) - __non_lin='NON' - for i in __lis : - if (dComp_incri[i]['RELATION']!='DIS_CHOC' and dComp_incri[i]['RELATION']!='ELAS'): - __non_lin='OUI' - break - # - # - if SCH_INI=='IMPLICITE': - dincri1=copy.copy(dincri) - dincri1[-1]['INST_FIN']= __L0[0] - nomres=DYNA_NON_LINE(MODELE =MODE, - CHAM_MATER =MATE, - CARA_ELEM =CARA, - EXCIT =dexct, - COMP_INCR =dComp_incri, - INCREMENT =dincri1, - SCHEMA_TEMPS=dschi, - NEWTON=dnew, - ETAT_INIT=dini, ) - __prc = 'IMPLICITE' - # - if SCH_INI=='EXPLICITE': - dincre1=copy.copy(dincre) - dincre1[-1]['INST_FIN']= __L0[0] - nomres=DYNA_NON_LINE(MODELE =MODE, - CHAM_MATER =MATE, - MASS_DIAG='OUI', - CARA_ELEM =CARA, - EXCIT =dexct, - COMP_INCR =dComp_incre, - INCREMENT =dincre1, - SCHEMA_TEMPS=dsche, - NEWTON=dnew, - ETAT_INIT=dini, ) - - __prc = 'EXPLICITE' - - # - __nb=len(__L0) - j = 1 - while 1: - # - if __prc=='IMPLICITE' : - __Ue=CREA_CHAMP(OPERATION='EXTR', PRECISION=1.E-7, RESULTAT=nomres, - TYPE_CHAM='NOEU_DEPL_R', NOM_CHAM='DEPL', INST=__L0[j-1],) - # - __Ve=CREA_CHAMP(OPERATION='EXTR', PRECISION=1.E-7, RESULTAT=nomres, - TYPE_CHAM='NOEU_DEPL_R', NOM_CHAM='VITE', INST=__L0[j-1],) - # - __Ae=CREA_CHAMP(OPERATION='EXTR', PRECISION=1.E-7, RESULTAT=nomres, - TYPE_CHAM='NOEU_DEPL_R', NOM_CHAM='ACCE', INST=__L0[j-1],) - # - __Ce=CREA_CHAMP(OPERATION='EXTR', PRECISION=1.E-7, RESULTAT=nomres, - TYPE_CHAM='ELGA_SIEF_R', NOM_CHAM='SIEF_ELGA', INST=__L0[j-1],) - # - __Vae=CREA_CHAMP(OPERATION='EXTR', PRECISION=1.E-7, RESULTAT=nomres, - TYPE_CHAM='ELGA_VARI_R', NOM_CHAM='VARI_ELGA', INST=__L0[j-1],) - dincre1=copy.copy(dincre) - dincre1[-1]['INST_FIN'] = __L0[j] - dincre1[-1]['INST_INIT']= __L0[j-1] - nomres=DYNA_NON_LINE(reuse=nomres, - MODELE=MODE, - MASS_DIAG='OUI', - CHAM_MATER=MATE, - CARA_ELEM=CARA, - EXCIT=dexct, - ETAT_INIT=_F(DEPL=__Ue, VITE=__Ve, ACCE=__Ae, - SIGM=__Ce, VARI=__Vae,), - COMP_INCR=dComp_incre, - INCREMENT=dincre1, - SCHEMA_TEMPS=dsche, - NEWTON=dnew,) - # - __prc='EXPLICITE' - j = j + 1 - bool = (j!=(__nb)) - if (not bool): break - # - if __prc=='EXPLICITE' : - # calcul sur la zone de recouvrement - print('calcul d''une solution explicite stabilisée') - __U1=CREA_CHAMP(OPERATION='EXTR', PRECISION=1.E-7, RESULTAT=nomres, - TYPE_CHAM='NOEU_DEPL_R', NOM_CHAM='DEPL', INST=__L0[j-1],) - # - __V1=CREA_CHAMP(OPERATION='EXTR', PRECISION=1.E-7, RESULTAT=nomres, - TYPE_CHAM='NOEU_DEPL_R', NOM_CHAM='VITE', INST=__L0[j-1],) - # - __A1=CREA_CHAMP(OPERATION='EXTR', PRECISION=1.E-7, RESULTAT=nomres, - TYPE_CHAM='NOEU_DEPL_R', NOM_CHAM='ACCE', INST=__L0[j-1],) - # - __C1=CREA_CHAMP(OPERATION='EXTR', PRECISION=1.E-7, RESULTAT=nomres, - TYPE_CHAM='ELGA_SIEF_R', NOM_CHAM='SIEF_ELGA', INST=__L0[j-1],) - # - __Va1=CREA_CHAMP(OPERATION='EXTR', PRECISION=1.E-7, RESULTAT=nomres, - TYPE_CHAM='ELGA_VARI_R', NOM_CHAM='VARI_ELGA', INST=__L0[j-1],) - # - __lrec=DEFI_LIST_REEL(DEBUT=__L0[j-1], - INTERVALLE=_F(JUSQU_A=(__L0[j-1])+(10*(__dtexp)), - PAS=__dtexp),) - __u_rec=DYNA_NON_LINE(MODELE=MODE, - CHAM_MATER=MATE, - MASS_DIAG='OUI', - CARA_ELEM=CARA, - EXCIT=dexct, - ETAT_INIT=_F(DEPL=__U1, VITE=__V1, ACCE=__A1, - SIGM=__C1, VARI=__Va1,), - COMP_INCR=dComp_incre, - INCREMENT=_F(LIST_INST=__lrec, - INST_INIT=__L0[j-1], - INST_FIN=(__L0[j-1])+(10*(__dtexp))), - SCHEMA_TEMPS=dscheq, - NEWTON=dnew,) - # - __Ui =CREA_CHAMP(OPERATION='EXTR', PRECISION=1.E-7, RESULTAT=__u_rec, - TYPE_CHAM='NOEU_DEPL_R', NOM_CHAM='DEPL', INST=(__L0[j-1])+(10*(__dtexp)),) - # - __Vi =CREA_CHAMP(OPERATION='EXTR', PRECISION=1.E-7, RESULTAT=__u_rec, - TYPE_CHAM='NOEU_DEPL_R', NOM_CHAM='VITE', INST=(__L0[j-1])+(10*(__dtexp)),) - # - __Ai =CREA_CHAMP(OPERATION='EXTR', PRECISION=1.E-7, RESULTAT=__u_rec, - TYPE_CHAM='NOEU_DEPL_R', NOM_CHAM='ACCE', INST=(__L0[j-1])+(10*(__dtexp)),) - # - # equilibrage du premier pas implicite - print('equilibrage du pas explicite stabilisée') - dincri1=copy.copy(dincri) - dincri1[-1]['INST_FIN'] = ((__L0[j-1])+(10*(__dtexp))) - dincri1[-1]['INST_INIT']= (__L0[j-1]) - nomres=DYNA_NON_LINE(reuse=nomres, - MODELE=MODE, - CHAM_MATER=MATE, - CARA_ELEM=CARA, - EXCIT=dexct, - ETAT_INIT=_F(DEPL=__Ui, VITE=__Vi, ACCE=__Ai, - SIGM=__C1, VARI=__Va1,), - COMP_INCR=dComp_incri, - INCREMENT=dincri1, - SCHEMA_TEMPS=dschi, - NEWTON=dnew,) - # - __Ui =CREA_CHAMP(OPERATION='EXTR', PRECISION=1.E-7, RESULTAT=nomres, - TYPE_CHAM='NOEU_DEPL_R', NOM_CHAM='DEPL', INST=(__L0[j-1])+(10*(__dtexp)),) - # - __Vi =CREA_CHAMP(OPERATION='EXTR', PRECISION=1.E-7, RESULTAT=nomres, - TYPE_CHAM='NOEU_DEPL_R', NOM_CHAM='VITE', INST=(__L0[j-1])+(10*(__dtexp)),) - # - __Ai =CREA_CHAMP(OPERATION='EXTR', PRECISION=1.E-7, RESULTAT=nomres, - TYPE_CHAM='NOEU_DEPL_R', NOM_CHAM='ACCE', INST=(__L0[j-1])+(10*(__dtexp)),) - # - __Ci =CREA_CHAMP(OPERATION='EXTR', PRECISION=1.E-7, RESULTAT=nomres, - TYPE_CHAM='ELGA_SIEF_R', NOM_CHAM='SIEF_ELGA', INST=(__L0[j-1])+(10*(__dtexp)),) - # - __Vai=CREA_CHAMP(OPERATION='EXTR', PRECISION=1.E-7, RESULTAT=nomres, - TYPE_CHAM='ELGA_VARI_R', NOM_CHAM='VARI_ELGA', INST=(__L0[j-1])+(10*(__dtexp)),) - # - print('calcul implicite après équilibrage') - dincri1=copy.copy(dincri) - dincri1[-1]['INST_FIN'] = __L0[j] - dincri1[-1]['INST_INIT']= ((__L0[j-1])+(10*(__dtexp))) - nomres=DYNA_NON_LINE(reuse=nomres, - MODELE=MODE, - CHAM_MATER=MATE, - CARA_ELEM=CARA, - EXCIT=dexct, - ETAT_INIT=_F(DEPL=__Ui, VITE=__Vi, ACCE=__Ai, - SIGM=__Ci, VARI=__Vai, - ), - COMP_INCR=dComp_incri, - INCREMENT=dincri1, - SCHEMA_TEMPS=dschi, - NEWTON=dnew,) - # - __prc='IMPLICITE' - j = j + 1 - bool = (j!=(__nb)) - if (not bool): break - # - return ier diff --git a/InterfaceTK/Interp.py b/InterfaceTK/Interp.py deleted file mode 100644 index 8fb95820..00000000 --- a/InterfaceTK/Interp.py +++ /dev/null @@ -1,153 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== - -import Tkinter,ScrolledText -import os, sys, string, traceback -import code - -sys.ps1 = ">>> " -sys.ps2 = "... " - -class PythonInterpreter( code.InteractiveConsole): - def __init__( self, text, namespace = None): - code.InteractiveConsole.__init__( self, namespace) - self.text = text - - def showtraceback( self): - start = self.text.pos + " - 1 lines" - code.InteractiveConsole.showtraceback( self) - end = self.text.pos - self.text.tag_add( "exception", start, end) - -class InterpWindow(Tkinter.Toplevel): - def __init__(self,namespace, parent=None): - Tkinter.Toplevel.__init__(self,parent) - self._initTkWidgets() - self.stdout = self.stderr = self - self.pos = '1.0' - self.history = [ '' ] - self.hpos = 0 - self.tabCount = 0 - self.shell = PythonInterpreter( self,namespace) - self.write("Python %s on %s\n%s\n(%s)\n" % - (sys.version, sys.platform, sys.copyright, - self.__class__.__name__)) - self.write( sys.ps1) - self.text.focus_set() - - def _initTkWidgets( self): - self.text = ScrolledText.ScrolledText( self, bg = "white",fg="black", wrap="word") - self.text.pack( fill='both', expand = 1) - self.text.bind( '', self.clearMsg) - self.text.bind( '', self.inputhandler) - self.text.bind( '', self.inputhandler) - self.text.bind( '', self.uphistory) - self.text.bind( '', self.downhistory) - self.text.bind( '', self.goto_sol) - self.text.bind( '', self.sendeof) - self.text.tag_config("exception", foreground = "red") - - def swapStdFiles(self): - sys.stdout,self.stdout = self.stdout,sys.stdout - sys.stderr,self.stderr = self.stderr,sys.stderr - - def write(self, data): - self.text.insert("end", data) - self.pos = self.text.index("end - 1 char") - self.text.yview_pickplace("end") - - def tag_add( self, tag, start, end): - self.text.tag_add( tag, start, end) - - def inputhandler(self, *args): - # Remove any extraneous stuff - self.text.delete( self.pos + " lineend", "end") - # Now get the line - line = self.text.get(self.pos, "end - 1 char") - self.text.insert("end", "\n") - self.pos = self.text.index("end") - self.addHistory( line) - self.swapStdFiles() - if self.shell.push( line): - self.write(sys.ps2) - else: - self.write(sys.ps1) - self.swapStdFiles() - self.text.mark_set("insert", "end") - return "break" - - def addHistory( self, line): - if line: - self.history.insert( len( self.history) - 1, line) - self.hpos = len( self.history) - 1 - - def sendeof(self, *args): - self.destroy() - return "break" - - def uphistory(self, event=None): - if not self.history: return "break" - - if self.hpos > 0: - self.hpos = self.hpos - 1 - - line = self.history[ self.hpos] - self.text.delete( self.pos, "end") - self.text.insert( self.pos, line) - - return "break" - - def downhistory( self, event=None): - if not self.history: return "break" - - if self.hpos < (len( self.history) - 1): - self.hpos = self.hpos + 1 - - line = self.history[ self.hpos] - self.text.delete( self.pos, "end") - self.text.insert( self.pos, line) - - return "break" - - def goto_sol( self, event=None): - """ - Met en mode edition la ligne courante - """ - self.text.mark_set( 'insert', 'insert linestart + 4 chars') - return "break" - - def clearMsg( self, event=None): - index = self.text.index( "insert") - self.text.delete( "insert lineend", "end") - self.tabCount = 0 - -if __name__ == "__main__": - app = Tkinter.Tk() - d={'a':1} - - def go(): - InterpWindow(d,parent=app) - - Tkinter.Button(app,text="Interp",command=go).pack() - Tkinter.Button(app,text="Quit",command=app.destroy).pack() - - app.mainloop() - diff --git a/InterfaceTK/TroisDPal.py b/InterfaceTK/TroisDPal.py deleted file mode 100644 index c0cc0d07..00000000 --- a/InterfaceTK/TroisDPal.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -""" - Ce module contient la classe 3Dpilote qui va creer les ordres - de pilotage de l idl PAL pour un element de structure -""" -import generator - -class TroisDPilote: - - def __init__(self,node,appli,parent): - self.node=node - self.appli=appli - self.parent=parent - - def envoievisu(self): - """ - """ - format="vers3DSalome" - if generator.plugins.has_key(format): - # Le generateur existe on l'utilise - g=generator.plugins[format]() - g.init_jdc(self.node.get_jdc()) - texte=g.gener(self.node) - else: - print "Le generateur n a pas ete trouvé" - print "Erreur ! Erreur!" - return "" - self.appli.envoievisu(texte) - diff --git a/InterfaceTK/__init__.py b/InterfaceTK/__init__.py deleted file mode 100644 index 28da2d3d..00000000 --- a/InterfaceTK/__init__.py +++ /dev/null @@ -1,20 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== diff --git a/InterfaceTK/appli.py b/InterfaceTK/appli.py deleted file mode 100644 index 147a560f..00000000 --- a/InterfaceTK/appli.py +++ /dev/null @@ -1,458 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -""" - Ce module contient la classe APPLI qui est la classe mère de - l'application EFICAS. Elle prend en charge l'organisation générale - des composants graphiques et l'initialisation Tk - L'aspect applicatif doit etre pris en charge par la classe dérivée -""" -# Modules Python -import os -import string -import sys -import types -import Pmw -import Tkinter -from widgets import showerror - -# Modules Eficas -import splash -import prefs -import styles -from styles import style -import fontes -import tooltip -import properties -import convert,generator -from Editeur import comploader -from Editeur.utils import extension_fichier,stripPath - -from widgets import Fenetre -from Misc import MakeNomComplet -from Editeur import session - -import listeFichiers -import listePatronsTK - -REPTK=os.path.dirname(os.path.abspath(__file__)) -sys.path[:0]=[REPTK] - -VERSION="EFICAS v1.14" - -class APPLI: - def __init__ (self,master,code=prefs.code,fichier=None,test=0,ihm="TK",salome=0) : - self.ihm=ihm - self.code=code - self.salome=salome - self.top=master - self.top.protocol("WM_DELETE_WINDOW",self.exitEFICAS) - - #dimensionnement de la fenetre principale - #aspect ratio de l'ecran - aspect=float(self.top.winfo_screenwidth())/float(self.top.winfo_screenheight()) - #resolution (pixels par point). On utilise le fait qu'on a "normalement" 72 points par inch - resolution= self.top.winfo_screenwidth()/(self.top.winfo_screenmmwidth()/25.4*72) - DDY=max(20,resolution*(fontes.standard[1]+4)) #largeur d'un caractere fonte standard en pixel - x=int(45*DDY) #largeur d'ouverture de 45 caracteres de fonte standard - y=int(25*DDY) #hauteur d'ouverture de 25 caracteres de fonte standard - minx=x*8/10 #largeur min (80 pour cent de largeur) - miny=y*8/10 #hauteur min (80 pour cent de hauteur) - self.top.minsize(minx,miny) - self.top.geometry('%dx%d' % (x,y)) - - self.top.title(VERSION + ' pour '+self.code) - self.titre=VERSION + ' pour '+self.code - self.top.withdraw() - self.initializeTk(master) - Pmw.initialise(master) - - self.dict_reels={} - self.liste_simp_reel=[] - # L'attribut test permet d'activer les panneaux de splash et d'erreur (test=0) - # Si test est different de 0, les panneaux ne sont pas activés - self.test=test - - # Lecture des parametres de configuration (fichier global editeur.ini - # et utilisateur eficas.ini) - self.lecture_parametres() - - self.format_fichier = Tkinter.StringVar() - self.message='' - # Avant la creation du bureau qui lit le catalogue - self.version_code=session.d_env.cata - - # Creation de la menubar, toolbar, messagebar - self.cree_composants_graphiques() - # Creation des autres composants graphiques dont le bureau (parametrable par prefs.py) - self.load_appli_composants() - self.listeFichiers=listeFichiers.listeFichiers(self) - self.listePatrons=listePatronsTK.listePatronsTK(self) - self.dir=None - - # Fermer le splash et deiconifier la fenetre principale si on n'est pas en test - if (self.test == 0): - splash.fini_splash() - #self.affiche_FAQ() - - # Ouverture des fichiers de commandes donnes sur la ligne de commande - cwd=os.getcwd() - self.dir=cwd - for study in session.d_env.studies: - os.chdir(cwd) - d=session.get_unit(study,self) - self.bureau.openJDC(file=study["comm"],units=d) - - - def send_message(self,message): - self.message=message - - def exitEFICAS(self): - self.quit() - - def quit(self): - if self.top: - self.top.quit() - - def lecture_parametres(self): - """ - Active la lecture des paramètres standards et utilisateur - """ - if (self.test == 0): - splash._splash.configure(text = "Chargement des paramètres utilisateur") - from Editeur import configuration - self.CONFIGURATION = configuration.make_config(self,prefs.REPINI) - self.CONFIGStyle = configuration.make_config_style(self,prefs.REPINI) - - def cree_composants_graphiques(self): - """ - Cree les constituants graphiques fixes de l'application : - - menubar - - toolbar - - statusbar - """ - if (self.test == 0): - splash._splash.configure(text = "Chargement de l'IHM") - splash._splash.configure(text = "Chargement de la menubar") - import menubar - self.menubar=menubar.MENUBAR(self,self.top) - if (self.test == 0): - splash._splash.configure(text = "Chargement de la toolbar") - import toolbar - self.toolbar=toolbar.TOOLBAR(self,self.top) - if (self.test == 0): - splash._splash.configure(text = "Chargement de la statusbar") - import statusbar - self.statusbar=statusbar.STATUSBAR(self.top,styles.style.statusfont) - - def load_appli_composants(self): - """ - Cree les autres constituants graphiques de l'application : - - bureau - - readercata - - ... - Cette creation est parametrable par fichier prefs.py - """ - if (self.test == 0): - splash._splash.configure(text = "Chargement des appli_composants") - for mname in self.appli_composants: - self.load_appli_composant(mname) - - def load_appli_composant(self,mname): - module=__import__(mname,globals(),locals()) - factory=getattr(module,mname.upper()) - appli_composant=factory(self,self.top) - setattr(self,mname,appli_composant) - self.fill_menus(appli_composant,appli_composant.menu_defs) - self.toolbar.creer_boutons_appli_composant(appli_composant.button_defs,appli_composant) - - def affiche_FAQ(self): - import faq - faq.affiche(self.top) - - def affiche_infos(self,message): - self.statusbar.affiche_infos(message) - return - - def initializeTk(self, root): - """ - Initialize platform specific options - """ - if sys.platform == 'mac': - self.initializeTk_mac(root) - elif sys.platform == 'win32': - self.initializeTk_win32(root) - else: - self.initializeTk_unix(root) - - def initializeTk_win32(self, root): - root.option_add('*Font', fontes.standard) - root.option_add('*EntryField.Entry.Font', fontes.standard) - root.option_add('*Listbox*Font',fontes.standard) - - def initializeTk_colors_common(self, root): - root.option_add('*background', style.background) - root.option_add('*foreground', style.foreground) - root.option_add('*EntryField.Entry.background', style.entry_background) - root.option_add('*Entry*background', style.entry_background) - root.option_add('*Listbox*background', style.list_background) - root.option_add('*Listbox*selectBackground', style.list_select_background) - root.option_add('*Listbox*selectForeground', style.list_select_foreground) - - def initializeTk_mac(self, root): - self.initializeTk_colors_common(root) - - def initializeTk_unix(self, root): - root.option_add('*Font', fontes.standard) - root.option_add('*EntryField.Entry.Font',fontes.standard ) - root.option_add('*Listbox*Font', fontes.standard) - self.initializeTk_colors_common(root) - - def get_texte_infos(self): - """ - Retourne un texte d'informations sur la session courante d'EFICAS - """ - texte = VERSION + '\n\n' - texte = texte + 'EFICAS est un produit développé par \nEDF-R&D\n' - texte = texte + 'Equipe : SINETICS\n\n' - texte = texte + 'Code utilisé : %s version %s\n' % (self.code,properties.version) - return texte - - def efface_aide(self,event): - """ - Efface la bulle d'aide d'un panneau - """ - try: - self.aide.destroy() - except: - pass - return - - def affiche_aide(self,event,aide): - """ - Affiche l'aide concernant un panneau - """ - x=event.x - y=event.y - widget=event.widget - self.aide=tooltip.TOOLTIP(widget) - self.aide.xoffset = 10 - self.aide.yoffset = - widget.winfo_height()/2 - self.aide.setText(aide) - self.aide._showTip() - return - - def cree_menu(self,menu,itemlist,appli_composant): - """ - Ajoute les items du tuple itemlist - dans le menu menu - """ - number_item=0 - radio=None - for item in itemlist: - number_item=number_item + 1 - raccourci_label="" - if not item : - #menu.add_separator() - pass - else: - if len(item)==3: - raccourci=item[2] - raccourci_label=" "+raccourci - newitem=(item[0],item[1]) - else : - if len(item)==4: - raccourci=item[2] - raccourci_label=" "+item[3] - newitem=(item[0],item[1]) - else : - raccourci="" - newitem=item - item=newitem - label,method=item - if type(method) == types.TupleType: - # On a un tuple => on cree une cascade - menu_cascade=Tkinter.Menu(menu) - menu.add_cascade(label=label,menu=menu_cascade) - self.cree_menu(menu_cascade,method,appli_composant) - elif method[0] == '&': - # On a une chaine avec & en tete => on cree un radiobouton - command=getattr(appli_composant,method[1:]) - menu.add_radiobutton(label=label,command=command) - if radio == None:radio=number_item - else: - command=getattr(appli_composant,method) - menu.add_command(label=label,accelerator=raccourci_label,command=command) - if raccourci != "" : - self.top.bind(raccourci,command) - # Si au moins un radiobouton existe on invoke le premier - if radio:menu.invoke(radio) - - def fill_menus(self,appli_composant,defs): - menudict=self.menubar.menudict - for mname,itemlist in defs: - if mname in menudict.keys() : - menu=menudict[mname] - else : - continue - self.cree_menu(menu,itemlist,appli_composant) - - def update_jdc_courant(self): - self.bureau.update_jdc_courant() - - def affiche_alerte(self,titre,message): - f=Fenetre(self, titre="Compte-rendu d'erreur", texte = titre + "\n\n" + message) - f.wait() - - -class valeur: - def __init__(self,v=None): - self.v=v - def set(self,v): - self.v=v - def get(self): - return self.v - -class STANDALONE(APPLI): - def __init__ (self,code=prefs.code,fichier=None,version='v8.2',ihm="TK") : - self.ihm=ihm - self.salome=0 - self.code=code - self.top=None - self.format_fichier=valeur() - - self.dict_reels={} - self.liste_simp_reel=[] - # L'attribut test doit valoir 1 si on ne veut pas creer les fenetres - self.test=1 - self.titre="STANDALONE POUR TEST" - - # Lecture des parametres de configuration (fichier global editeur.ini - # et utilisateur eficas.ini) - self.lecture_parametres() - - self.message='' - # Avant la creation du bureau qui lit le catalogue - self.version_code=version - import readercata - self.readercata=readercata.READERCATA(self,None) - - self.dir=None - - def affiche_infos(self,message): - return - - def get_text_JDC(self,JDC,format): - if generator.plugins.has_key(format): - # Le generateur existe on l'utilise - g=generator.plugins[format]() - jdc_formate=g.gener(JDC,format='beautifie') - return jdc_formate - else: - # Il n'existe pas c'est une erreur - return - - def newJDC(self): - CONTEXT.unset_current_step() - J=self.readercata.cata[0].JdC(procedure="", - appli=self, - cata=self.readercata.cata, - cata_ord_dico=self.readercata.cata_ordonne_dico, - rep_mat=self.CONFIGURATION.rep_mat, - ) - J.analyse() - return J - - def openJDC(self,file): - self.fileName = file - e=extension_fichier(file) - self.JDCName=stripPath(file) - self.initialdir = os.path.dirname(os.path.abspath(file)) - format=self.format_fichier.get() - # Il faut convertir le contenu du fichier en fonction du format - if convert.plugins.has_key(format): - # Le convertisseur existe on l'utilise - p=convert.plugins[format]() - p.readfile(file) - text=p.convert('exec',self) - if not p.cr.estvide(): - raise ValueError(str(p.cr)) - - # On se met dans le repertoire ou se trouve le fichier de commandes - # pour trouver les eventuels fichiers include ou autres - # localises a cote du fichier de commandes - os.chdir(self.initialdir) - CONTEXT.unset_current_step() - J=self.readercata.cata[0].JdC(procedure=text, - appli=self, - cata=self.readercata.cata, - cata_ord_dico=self.readercata.cata_ordonne_dico, - nom=self.JDCName, - rep_mat=self.CONFIGURATION.rep_mat, - ) - J.analyse() - txt= J.cr.get_mess_exception() - if txt:raise ValueError(txt) - return J - - def openTXT(self,text): - self.JDCName="TEXT" - CONTEXT.unset_current_step() - J=self.readercata.cata[0].JdC(procedure=text, - appli=self, - cata=self.readercata.cata, - cata_ord_dico=self.readercata.cata_ordonne_dico, - nom=self.JDCName, - rep_mat=self.CONFIGURATION.rep_mat, - ) - J.analyse() - txt= J.cr.get_mess_exception() - if txt:raise ValueError(txt) - return J - - def create_item(self,obj): - return comploader.make_objecttreeitem(self,getattr(obj,"nom","item"),obj) - - def get_file(self,unite=None,fic_origine = ''): - """ - Retourne le nom du fichier correspondant a l unite logique unite (entier) - ou d'un fichier poursuite - """ - f,ext=os.path.splitext(fic_origine) - if unite : - #include - finclude=f+".%d" % unite - else: - #poursuite - n=ext[-1] - if n == '0': - ext=".comm" - else: - ext=".com%d" % (string.atoi(n)-1) - if ext == '.com0' and not os.path.isfile(f+".com0"): - ext=".comm" - finclude=f+ext - ff=open(finclude) - text=ff.read() - ff.close() - return finclude,text - - def affiche_alerte(self,titre,message): - print titre+ "\n\n" + message diff --git a/InterfaceTK/basestyle.py b/InterfaceTK/basestyle.py deleted file mode 100644 index e4287b75..00000000 --- a/InterfaceTK/basestyle.py +++ /dev/null @@ -1,27 +0,0 @@ -class STYLE: - background='gray90' - foreground='black' - entry_background='white' - list_background='white' - list_select_background='#00008b' - list_select_foreground='grey' - tooltip_background="yellow" - - standard = ("Helvetica",12) - standard_italique = ("Helvetica",12,'italic') - standard_gras = ("Helvetica",12,'bold') - standard_gras_souligne = ("Helvetica",12,'bold','underline') - - canvas = ('Helvetica',10) - canvas_italique = ('Helvetica',10,'italic') - canvas_gras = ("Helvetica",10,'bold') - canvas_gras_italique = ("Helvetica",12,'bold','italic') - - standard12 = ("Helvetica",14) - standard12_gras = ("Helvetica",14,'bold') - standard12_gras_italique = ( "Helvetica",14,'bold','italic') - - standardcourier10 = ("Courier",14) - statusfont = ("Helvetica",16) - -style=STYLE() diff --git a/InterfaceTK/browser.py b/InterfaceTK/browser.py deleted file mode 100644 index 51c4e3a4..00000000 --- a/InterfaceTK/browser.py +++ /dev/null @@ -1,65 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -""" -""" -# Modules Python -import os,string - -# Modules Eficas -import Interp -import catabrowser -import cataediteur - -class BROWSER: - - menu_defs=[ - ('Browsers',[ - ('Browser catalogue','browser_catalogue'), - ('Editeur catalogue','edite_catalogue'), - ('Shell','shell'), - ] - ) - ] - - button_defs=[] - - def __init__(self,appli,parent): - self.appli=appli - self.parent=parent - self.cataitem = catabrowser.CATAItem(self,"Catalogue "+self.appli.readercata.code, - self.appli.readercata.cata, - objet_cata_ordonne = self.appli.readercata.cata_ordonne_dico) - - def shell(self,event=None): - if not hasattr(self.appli.bureau.JDCDisplay_courant,'jdc'):return - d={'j':self.appli.bureau.JDCDisplay_courant.jdc} - Interp.InterpWindow(d,parent=self.parent) - - def browser_catalogue(self,event=None): - catabrowser.CataBrowser(parent=self.parent,appli=self.appli, - cata = self.appli.readercata.cata, - item = self.cataitem) - - def edite_catalogue(self,event=None): - cataediteur.CataEditeur(parent=self.parent,appli=self.appli,cata=self.appli.readercata.cata) - - - diff --git a/InterfaceTK/bureau.py b/InterfaceTK/bureau.py deleted file mode 100644 index 5921a2d5..00000000 --- a/InterfaceTK/bureau.py +++ /dev/null @@ -1,817 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -""" - Ce module contient la classe BUREAU qui gere les JDC ouverts -""" -# Modules Python -import os,string,sys,re -import traceback -import Pmw -from widgets import askopenfilename,asksaveasfilename -from widgets import showinfo,askyesno,showerror - -# Modules Eficas -import splash -import prefs -import convert -import generator -import AIDE -import os -from jdcdisplay import JDCDISPLAY -from Editeur.utils import extension_fichier,stripPath,save_in_file -from widgets import Fenetre,Ask_Format_Fichier,FenetreSurLigneWarning -from fenetre_mc_inconnus import fenetre_mc_inconnus -from Ihm import CONNECTOR -try : - from Traducteur import traduitV7V8 -except : - pass - -from Editeur import comploader - -dict_defext = {"ASTER":".comm","HOMARD":".py","OPENTURNS":".comm"} -dict_filtyp = {"ASTER":(("ASTER", ".comm"),),"HOMARD":(("HOMARD", ".py"),),"OPENTURNS":(("OPENTURNS", ".comm"),)} - -class BUREAU: - menu_defs=[ - ('Fichier',[ - ('Nouveau','newJDC',''), - ('Ouvrir','openJDC',''), - ('Enregistrer','saveJDC',''), - ('Enregistrer sous','saveasJDC',''), - None, - ('Fermer','closeJDC',''), - ('Quitter','exitEFICAS',''), - ] - ), - ('Edition',[ - ('Copier','copy',''), - ('Couper','cut',''), - ('Coller','paste',''), - ] - ), - ('Jeu de commandes',[ - ('Rapport de validation','visuCRJDC',''), - ('Fichier a plat','visu_a_plat',''), - ('Fichier .py','visuJDC_py'), - ('Fichier source','visu_txt_brut_JDC',''), - ('Parametres Eficas','affichage_fichier_ini'), - ('Mots-cles inconnus','mc_inconnus'), - ] - ), - ('Traduction',[ - ('Traduction v7 en v8','TraduitFichier','','Ctrl+T') - ] - ), - ('Aide',[ - ('Aide EFICAS','aideEFICAS','','Ctrl+A'), - ] - ), - ] - - button_defs = (('New24',"newJDC","Creation d'un nouveau fichier",'always'), - ('Open24',"openJDC","Ouverture d'un fichier existant",'always'), - ('Save24',"saveJDC","Sauvegarde du fichier courant",'always'), - ('Fermer24',"closeJDC","Fermeture du fichier courant",'always'), - ('Zoom24',"visuJDC","Visualisation du fichier de commandes",'always'), - None, - ('Copy24',"copy","Copie l'objet courant",'jdc'), - ('Cut24',"cut","Coupe l'objet courant",'jdc'), - ('Paste24',"paste","Colle l'objet copie apres l'objet courant",'jdc'), - None, - ('Delete24',"delete","Supprime l'objet courant",'jdc'), - ('Help24',"view_doc","Documentation de l'objet courant",'jdc') - ) - try: - menu_defs=prefs.menu_defs['bureau'] - except: - pass - try: - button_defs=prefs.button_defs['bureau'] - except: - pass - - def __init__(self,appli,parent): - self.parent=parent - self.appli=appli - if self.appli.test == 0 : - splash._splash.configure(text = "Creation du bureau") - self.nb = Pmw.NoteBook(self.parent,raisecommand=self.selectJDC) - self.nb.pack(fill='both',expand=1) - self.JDCDisplay_courant=None - self.fileName=None - self.liste_JDCDisplay=[] - self.charger_composants() - self.cree_cataitem() - self.text_reel="" - self.initialdir = self.appli.CONFIGURATION.initialdir - - def charger_composants(self): - comploader.charger_composants() - - def cree_cataitem(self): - """ - On recupere dans l'appli_composant readercata les variables - qui servent par la suite pour la creation des JDC - """ - self.cataitem=self.appli.readercata.cataitem - self.cata=self.appli.readercata.cata - self.cata_ordonne_dico=self.appli.readercata.cata_ordonne_dico - self.code=self.appli.readercata.code - self.version_code=self.appli.readercata.version_code - self.fic_cata=self.appli.readercata.fic_cata - - def selectJDC(self,event=None): - """ - Cette methode est appelee chaque fois que l'on selectionne - l'onglet d'un JDC dans le NoteBook des JDC. - Elle permet de stocker dans les variable self.JDC et - self.JDCDisplay_courant les valeurs concernant le JDC courant - """ - if len(self.liste_JDCDisplay) == 0 : return - #if self.JDCDisplay_courant : self.JDCDisplay_courant.jdc.unset_context() - numero_jdc = self.nb.index(self.nb.getcurselection()) - self.JDCDisplay_courant.unselect() - self.JDCDisplay_courant = self.liste_JDCDisplay[numero_jdc] - self.JDC = self.JDCDisplay_courant.jdc - self.JDCName = self.JDC.nom - self.JDCDisplay_courant.select() - #print "selectJDC",numero_jdc,self.JDCDisplay_courant,self.JDCName - - - def newJDC_include(self,event=None): - """ - Initialise un nouveau JDC include vierge - """ - import Extensions.jdc_include - JdC_aux=Extensions.jdc_include.JdC_include - - self.appli.statusbar.reset_affichage_infos() - - CONTEXT.unset_current_step() - jaux=self.cata[0].JdC(procedure="",appli=self.appli, - cata=self.cata,cata_ord_dico=self.cata_ordonne_dico, - rep_mat=self.appli.CONFIGURATION.rep_mat, - ) - jaux.analyse() - - J=JdC_aux(procedure="",appli=self.appli, - cata=self.cata,cata_ord_dico=self.cata_ordonne_dico, - jdc_pere=jaux, - rep_mat=self.appli.CONFIGURATION.rep_mat, - ) - J.analyse() - self.JDCName=J.nom - self.fileName=None - self.ShowJDC(J,self.JDCName) - self.appli.toolbar.active_boutons() - return J - - def newJDC(self,event=None): - """ - Initialise un nouveau JDC vierge - """ - self.appli.statusbar.reset_affichage_infos() - - CONTEXT.unset_current_step() - J=self.cata[0].JdC(procedure="",appli=self.appli, - cata=self.cata,cata_ord_dico=self.cata_ordonne_dico, - rep_mat=self.appli.CONFIGURATION.rep_mat, - ) - J.analyse() - self.JDCName=J.nom - self.fileName=None - self.ShowJDC(J,self.JDCName) - self.appli.toolbar.active_boutons() - return J - - def ShowJDC(self,JDC,nom,label_onglet=None,JDCDISPLAY=JDCDISPLAY,enregistre="non"): - """ - Lance l'affichage du JDC cad creation du JDCDisplay - Rajoute le JDCDisplay a la liste des JDCDisplay si label_onglet == None cad si on cree - bien un nouveau JDCDisplay et non si on remplace (renommage de l'onglet) - """ - self.JDC=JDC - self.JDCName = self.JDC.nom = nom - if label_onglet == None : - # On veut un nouvel onglet - label_onglet = self.GetLabelJDC() - self.nb.add(label_onglet,tab_text = nom,tab_width=20) - new = 'oui' - else : - new = 'non' - self.JDCDisplay_courant=JDCDISPLAY(self.JDC,nom,appli=self.appli,parent=self.nb.page(label_onglet)) - if new == 'oui': - self.liste_JDCDisplay.append(self.JDCDisplay_courant) - self.JDCDisplay_courant.modified='n' - if enregistre != "non" : - self.JDCDisplay_courant.fichier=self.fileName - else : - self.initialdir = self.appli.CONFIGURATION.rep_user - self.nb.selectpage(label_onglet) - self.nb.setnaturalsize() - self.nb.bind_all("",lambda e,s=self:s.selectArbreDown()) - self.nb.bind_all("",lambda e,s=self:s.selectArbreUp()) - self.nb.bind_all("",lambda e,s=self:s.deplieReplieNode()) - texte = "Jeu de commandes :" + self.JDCName+" ouvert" - CONNECTOR.Connect(JDC,"close",self.onClose,(self.JDCDisplay_courant,)) - self.appli.affiche_infos(texte) - - def onClose(self,jdcdisplay): - #print "onClose",jdcdisplay - self.closeJDCDISPLAY(jdcdisplay) - - def closeJDCDISPLAY(self,jdc): - """ - Ferme le jdcdisplay specifie par l'argument jdc - """ - if jdc is self.JDCDisplay_courant: - # on ferme le jdcdisplay courant - self.closeSelectedJDC() - else: - # on ferme un autre jdcdisplay que le courant - old_JDCDisplay=self.JDCDisplay_courant - old_page=self.nb.getcurselection() - - self.JDCDisplay_courant=jdc - self.JDC=jdc.jdc - numero_jdc=self.liste_JDCDisplay.index(jdc) - self.nb.selectpage(numero_jdc) - #print numero_jdc - - self.closeSelectedJDC() - self.JDCDisplay_courant=old_JDCDisplay - self.JDC=old_JDCDisplay.jdc - self.nb.selectpage(old_page) - - def closeJDC (self,event=None) : - """ - Ferme le JDC associe au JDCDISPLAY selectionne - """ - if self.JDCDisplay_courant : - self.JDCDisplay_courant.jdc.close() - - def closeSelectedJDC (self) : - """ - Ferme le JDC courant et detruit l'onglet associe dans le notebook self.nb - """ - if self.JDCDisplay_courant.modified == 'o' : - message = "Voulez-vous sauvegarder le jeu de commandes "+self.JDC.nom+" courant ?" - reponse = askyesno(title="Sauvegarde du jdc courant", - message=message) - if reponse : - test = self.saveJDC() - if test == 0 : - self.appli.affiche_infos("Sauvegarde impossible") - return - - CONNECTOR.Disconnect(self.JDCDisplay_courant.jdc,"close",self.onClose,(self.JDCDisplay_courant,)) - self.JDCDisplay_courant.supprime() - self.JDCDisplay_courant.jdc.supprime() - self.liste_JDCDisplay.remove(self.JDCDisplay_courant) - # Active le mecanisme de selection du notebook (selectJDC) - self.nb.delete(self.nb.getcurselection()) - - try: - index = self.nb.index(self.nb.getcurselection()) - self.JDCDisplay_courant = self.liste_JDCDisplay[index] - self.JDC = self.JDCDisplay_courant.jdc - except: - self.JDC = None - self.JDCDisplay_courant = None - self.appli.toolbar.inactive_boutons() - - def visuCRJDC(self,event=None): - return self.visuCR(mode='JDC') - - def visuCR(self,mode): - """ - Methode permettant l'affichage du rapport de validation - """ - if mode == 'JDC': - if not hasattr(self,'JDC') : return - if self.JDC == None : return - titre="rapport de validation du jeu de commandes courant" - cr = self.JDC.report() - #self.update_jdc_courant() - elif mode == 'CATA': - from Noyau.N_CR import CR - cr = CR() - cr.debut = "Debut rapport de validation du catalogue" - cr.fin = "Fin rapport de validation du catalogue" - titre="rapport de validation du catalogue" - if hasattr(self,'cata_ordonne_cr') : - cr.add(self.cata_ordonne_cr) - if hasattr(self,'cata_dev_ordonne_cr') : - cr.add(self.cata_dev_ordonne_cr) - for cata in self.cata: - if hasattr(cata,'JdC'): - cr.add(cata.JdC.report()) - texte_cr = str(cr) - self.visu_texte_cr = Fenetre(self.appli,titre=titre,texte=texte_cr) - - def openJDC(self,event=None,file=None,units=None,enregistre="oui"): - """ - Demande a l'utilisateur quel JDC existant il veut ouvrir - """ - if self.code == 'ASTER': - filetypes = ( ("format "+self.appli.format_fichier.get(), ".com*"),("Tous",'*')) - elif self.code == 'HOMARD' : - filetypes = ( ("format "+self.appli.format_fichier.get(), ".py"),("Tous",'*')) - elif self.code == 'OPENTURNS' : - filetypes = ( ("format "+self.appli.format_fichier.get(), ".com*"),("Tous",'*')) - else: - filetypes = ( ("format "+self.appli.format_fichier.get(), ".py"),) - if not hasattr(self,'initialdir'): - self.initialdir = self.appli.CONFIGURATION.initialdir - - if not file : - file = askopenfilename(title="Ouverture d'un fichier de commandes Aster", - defaultextension=".comm", - filetypes = filetypes, - initialdir = self.initialdir) - if file : - self.fileName = file - e=extension_fichier(file) - self.JDCName=stripPath(file) - self.initialdir = os.path.dirname(os.path.abspath(file)) - else : - return - - # Il faut convertir le contenu du fichier en fonction du format - format=self.appli.format_fichier.get() - if convert.plugins.has_key(format): - # Le convertisseur existe on l'utilise - p=convert.plugins[format]() - p.readfile(file) - text=p.convert('exec',self.appli) - if not p.cr.estvide(): - self.appli.affiche_infos("Erreur a la conversion") - Fenetre(self.appli, - titre="compte-rendu d'erreurs, EFICAS ne sait pas convertir ce fichier", - texte = str(p.cr)).wait() - return - if enregistre == "oui" : - self.appli.listeFichiers.aOuvert(file) - else: - # Il n'existe pas c'est une erreur - self.appli.affiche_infos("Type de fichier non reconnu") - showerror("Type de fichier non reconnu","EFICAS ne sait pas ouvrir ce type de fichier") - return - - # On se met dans le repertoire ou se trouve le fichier de commandes - # pour trouver les eventuels fichiers include ou autres - # localises a cote du fichier de commandes - os.chdir(self.initialdir) - CONTEXT.unset_current_step() - J=self.cata[0].JdC(procedure=text,appli=self.appli, - cata=self.cata,cata_ord_dico=self.cata_ordonne_dico, - nom = self.JDCName, - rep_mat=self.appli.CONFIGURATION.rep_mat, - ) - if units is not None: - J.recorded_units=units - J.old_recorded_units=units - - J.analyse() - txt_exception = J.cr.get_mess_exception() - if txt_exception : - # des exceptions ont ete levees a la creation du JDC - # --> on affiche les erreurs mais pas le JDC - self.JDC=J - self.appli.affiche_infos("Erreur fatale au chargement de %s" %file) - if self.appli.test == 0 : - showerror("Erreur fatale au chargement d'un fichier",txt_exception) - else: - self.ShowJDC(J,self.JDCName,enregistre=enregistre) - self.appli.toolbar.active_boutons() - # si le JDC ne contient rien (vide), on retourne ici - if len(self.JDC.etapes) == 0 : return - # dans le cas ou le JDC est invalide, on affiche son CR - if not self.JDC.isvalid(): - self.appli.top.update() - self.visuCR(mode='JDC') - return J - - def deplieReplieNode(self): - self.JDCDisplay_courant.tree.tree.deplieReplieNode() - - def selectArbreDown(self): - self.JDCDisplay_courant.tree.tree.canvas.focus_set() - self.JDCDisplay_courant.tree.tree.mot_down_force() - - def selectArbreUp(self): - self.JDCDisplay_courant.tree.tree.canvas.focus_set() - self.JDCDisplay_courant.tree.tree.mot_up_force() - - def GetLabelJDC(self,nb_jdc = 'absent'): - """ - Retourne le label de l'onglet du NoteBook associe au JDC a afficher - """ - if nb_jdc == 'absent': - nb_jdc = len(self.nb.pagenames()) - nb_jdc = nb_jdc+1 - label_onglet = 'JDC'+`nb_jdc` - if label_onglet not in self.nb.pagenames() : - return label_onglet - else : - return self.GetLabelJDC(nb_jdc) - - def saveasJDC(self,event=None): - """ - Sauvegarde le JDC courant en demandant imperativement a l'utilisateur de - donner le nom du fichier de sauvegarde - """ - self.saveJDC(echo='oui') - - def saveJDC(self,echo='non'): - """ - Sauvegarde le JDC courant. - Retourne 1 si la sauvegarde s'est bien faite, 0 sinon. - - - Si echo = 'oui' : interactif (l'utilisateur donne le nom sous lequel il - veut sauver le JDC - - Si echo = 'non' : muet (sauvegarde le JDC dans JDC.procedure) - """ - ok = 0 - if not hasattr(self,'JDC') : return 0 - format=self.appli.format_fichier.get() - if generator.plugins.has_key(format): - # Le generateur existe on l'utilise - g=generator.plugins[format]() - jdc_formate=g.gener(self.JDC,format='beautifie') - if format == 'homard': - self.jdc_homard=g.get_homard() - elif format == 'openturns' : - self.jdc_openturn_xml=g.getOpenturnsXML() - self.jdc_openturn_std=g.getOpenturnsSTD() - if not g.cr.estvide(): - self.appli.affiche_infos("Erreur a la generation") - showerror("Erreur a la generation","EFICAS ne sait pas convertir ce JDC") - return - else: - # Il n'existe pas c'est une erreur - self.appli.affiche_infos("Format %s non reconnu" % format) - showerror("Format %s non reconnu" % format,"EFICAS ne sait pas convertir le JDC") - return - self.jdc_fini = string.replace(jdc_formate,'\r\n','\n') - - if echo =='oui' or self.JDCDisplay_courant.fichier == None: - ok = self.asknomsauvegardeJDC() - elif self.JDCDisplay_courant.fichier != None : - # le JDC a deja un nom : on sauvegarde directement sans demander - # un autre nom au developpeur - if not save_in_file(self.JDCDisplay_courant.fichier,self.jdc_fini,self.appli.dir) : - showinfo("Erreur","Probleme a la sauvegarde du fichier :" + `self.JDCDisplay_courant.fichier`) - #return 0 - ok = 0 - else : - if self.appli.format_fichier.get() == 'homard': - self.save_homard(self.JDCDisplay_courant.fichier,self.jdc_homard) - elif self.appli.format_fichier.get() == 'openturns': - self.save_openturns(self.JDCDisplay_courant.fichier[0:-3], - self.jdc_openturn_xml, - self.jdc_openturn_std) - self.JDCDisplay_courant.stop_modif() - self.appli.affiche_infos("sauvegarde de "+`self.JDCDisplay_courant.fichier`+" effectuee") - ok = 1 - - if ok and self.appli.salome: - # eficas a ete lance a partir deSalome - #1)ajout dans l'arbre d'etude du nom du jdc - if self.appli.salome==0 : return 0 - ok, msg = self.appli.addJdcInSalome( self.JDCDisplay_courant.fichier ) - - #2)CS_pbruno ?? - from panelsSalome import SALOME_UNIQUE_BASE_Panel - if len(SALOME_UNIQUE_BASE_Panel.dict_fichier_unite) > 0 : - print 'CS_pbruno if len(SALOMchier_unite) > 0 :???????' - self.appli.creeConfigTxt( self.appli.CONFIGURATION.initialdir, SALOME_UNIQUE_BASE_Panel.dict_fichier_unite ) - - #3)creation/mise a jours d'un maillage dans Salome - if self.code == 'ASTER': - self.appli.createOrUpdateMesh() - return ok - - def asknomsauvegardeJDC(self): - """ Demande a l'utilsateur le nom sous lequel il veut sauvegarder le JDC courant """ - titre = "Sauvegarde d'un fichier de commandes "+self.code - if dict_defext.has_key(self.code) : - defext = dict_defext[self.code] - filtyp = dict_filtyp[self.code] - else : - defext = ".py" - filtyp = ( (self.code, ".py"),) - sauvegarde = asksaveasfilename(title=titre, - defaultextension=defext, - filetypes = filtyp, - initialdir = self.initialdir) - #initialdir = self.appli.CONFIGURATION.initialdir) - #initialdir = self.appli.CONFIGURATION.rep_user) - if sauvegarde : - if not save_in_file(sauvegarde,self.jdc_fini,None) : - showinfo("Erreur","Probleme a la sauvegarde du fichier "+`sauvegarde`) - return 0 - else : - if self.appli.format_fichier.get() == 'homard': - self.save_homard(sauvegarde,self.jdc_homard) - elif self.appli.format_fichier.get() == 'openturns': - self.save_openturns(sauvegarde, - self.jdc_openturn_xml, - self.jdc_openturn_std) - self.JDCDisplay_courant.stop_modif() - self.appli.affiche_infos("Sauvegarde effectuee") - if sauvegarde != self.JDCDisplay_courant.fichier : - # l'utilisateur a sauvegarde le JDC sous un autre nom - self.JDCDisplay_courant.fichier = sauvegarde - self.JDCName = self.JDC.nom = stripPath(sauvegarde) - self.JDC.changefichier(sauvegarde) - self.changeNomPage() - return 1 - else : - return 0 - - def changeNomPage(self): - """ Change le nom de l'onglet contenant le JDC courant : en fait detruit l'actuel - et recree un autre onglet a la même place avec le bon nom - """ - nom = self.JDCName - self.JDCDisplay_courant.jdc.nom = nom - nom_page = self.nb.getcurselection() - num_page = self.nb.index(nom_page) - tab = self.nb.tab(num_page) - tab.configure(text = nom) - - def exitEFICAS(self,event=None): - """ - Permet de sortir d'EFICAS en demandant a l'utilisateur - s'il veut sauvegarder les modifications en cours - """ - liste = self.GetListeJDCaSauvegarder() - if liste != [] : - # Certains fichiers n'ont pas ete sauvegardes ... - if askyesno("Enregistrer modifications","Enregistrer les modifications ?") : - test = self.saveall(liste) - if test != 1 : - return - if askyesno ("Quitter","Voulez-vous vraiment quitter l'application ?") : - for JDCDisplay in self.liste_JDCDisplay: - JDCDisplay.jdc.supprime() - self.appli.quit() - return - - def GetListeJDCaSauvegarder(self) : - """ Retourne parmi la liste de tous les JDC ouverts la liste de ceux qui ont ete modifies """ - if not self.JDCDisplay_courant : return [] - if len(self.liste_JDCDisplay) == 0 : return l - l = [] - for JDCDisplay in self.liste_JDCDisplay: - if JDCDisplay.modified == 'o' : - l.append(JDCDisplay) - return l - - def copy(self,event=None): - """ - Lance la copie sur le JDC courant - """ - if self.JDCDisplay_courant : self.JDCDisplay_courant.doCopy() - - def paste(self,event=None): - """ - Lance le collage sur le JDC courant - """ - if self.JDCDisplay_courant : self.JDCDisplay_courant.doPaste() - - def cut(self,event=None): - """ - Lance le cut sur le JDC courant - """ - if self.JDCDisplay_courant: self.JDCDisplay_courant.doCut() - - def delete(self): - """ - Lance la suppression du noeud courant - """ - if not self.JDCDisplay_courant : return - self.JDCDisplay_courant.init_modif() - self.JDCDisplay_courant.node_selected.delete() - - def visuJDC_py(self,event=None): - """ - Methode permettant d'afficher dans une fenêtre a part l'echo au - format python du jdc courant - """ - if not hasattr(self,'JDC') : return - jdc_fini = self.get_text_JDC('python') - if jdc_fini == None : return - Fenetre(self.appli, - titre = 'fichier '+ self.JDCName + ' a la syntaxe Python', - texte = jdc_fini) - - def visuJDC(self): - """ - Methode permettant d'afficher dans une fenêtre a part l'echo au - format .comm ou .py du jdc courant - """ - if not hasattr(self,'JDC') : return - titre = 'fichier '+ self.JDCName + ' a la syntaxe '+ self.code - format=self.appli.format_fichier.get() - self.jdc_fini = self.get_text_JDC(format) - if self.jdc_fini == None : return - self.visu_fichier_cmd = Fenetre(self.appli,titre=titre,texte = self.jdc_fini) - - def get_text_JDC(self,format): - if generator.plugins.has_key(format): - # Le generateur existe on l'utilise - g=generator.plugins[format]() - jdc_formate=g.gener(self.JDC,format='beautifie') - if not g.cr.estvide(): - self.appli.affiche_infos("Erreur a la generation") - showerror("Erreur a la generation","EFICAS ne sait pas convertir ce JDC") - return - else: - return jdc_formate - else: - # Il n'existe pas c'est une erreur - self.appli.affiche_infos("Format %s non reconnu" % format) - showerror("Format %s non reconnu" % format,"EFICAS ne sait pas convertir le JDC en format %s "% format) - return - - def view_doc(self): - """ - Permet d'ouvrir le fichier doc U de la commande au format pdf avec Acrobat Reader - - Ne fonctionne pas sous UNIX (chemin d'acces Acrobat Reader) - - indication du chemin d'acces aux fichiers pdf a revoir : trop statique - """ - if not self.JDCDisplay_courant : return - try: - cle_doc = self.JDCDisplay_courant.node_selected.item.get_docu() - if cle_doc == None : return - cle_doc = string.replace(cle_doc,'.','') - cle_doc = string.replace(cle_doc,'-','') - commande = self.appli.CONFIGURATION.exec_acrobat - nom_fichier = cle_doc+".pdf" - fichier = os.path.abspath(os.path.join(self.appli.CONFIGURATION.path_doc,nom_fichier)) - if os.name == 'nt': - os.spawnv(os.P_NOWAIT,commande,(commande,fichier,)) - elif os.name == 'posix': - script ="#!/usr/bin/sh \n%s %s&" %(commande,fichier) - pid = os.system(script) - except AttributeError: - traceback.print_exc() - pass - - def visu_a_plat(self,event=None): - """ - Methode permettant d'afficher dans une fenêtre a part l'echo 'a plat' du jdc courant - """ - if not hasattr(self,'JDC') : return - titre = 'fichier '+ self.JDCName + ' a plat ' - self.jdc_fini = self.get_text_JDC('aplat') - if self.jdc_fini == None : return - self.visu_fichier_cmd = Fenetre(self.appli,titre=titre,texte = self.jdc_fini) - - def visu_txt_brut_JDC(self,event=None): - """ - Methode permettant d'afficher le jeu de commandes tel qu'il a ete passe au JDC - """ - if not hasattr(self,'JDC') : return - titre = "fichier de commandes utilisateur" - #texte = self.JDC.procedure - #if texte == None: - if self.JDCDisplay_courant.fichier == None: - self.appli.affiche_infos("Pas de fichier initial") - showerror("Impossible de visualiser le fichier initial", - "EFICAS ne peut visualiser le fichier initial.\nIl s'agit d'un nouveau JDC") - return - os.chdir(self.appli.dir) - f=open(self.JDCDisplay_courant.fichier,'r') - texte=f.read() - f.close() - self.visu_texte_JDC = Fenetre(self.appli,titre=titre,texte=texte) - - def affichage_fichier_ini(self): - """ - Affichage des valeurs des parametres relus par Eficas - """ - self.appli.CONFIGURATION.affichage_fichier_ini() - - def saveall(self,liste): - """ - Sauvegarde tous les JDC contenus dans liste - """ - test = 1 - for JDCDisplay in liste : - self.JDCDisplay_courant=JDCDisplay - self.JDC = JDCDisplay.jdc - test = test * self.saveJDC(echo = 'non') - return test - - def save_homard(self,nom,texte): - file_homard=nom+'.conf_homard' - try: - f=open(file_homard,'w') - for ligne in texte: - f.write(ligne) - f.write('\n') - f.close() - except: - print "Pb a la sauvegarde sous le format homard" - if self.appli.salome: - import eficasEtude - self.appli.salome.rangeInStudy(file_homard,"_CONF") - - def save_openturns(self,nom,texteXML,texteSTD): - nomSansSuf=nom[:nom.rfind(".")] - fileXML=nomSansSuf + '.xml' - fileSTD=nomSansSuf + '_Std.py' - try: - f=open(fileXML,'w') - f.write(texteXML) - f.close() - except: - print "Pb sauvegarde openturns pour le format xml" - try: - #print texteSTD - if nomSansSuf.rfind("/") > 0 : - nomSansSuf=nomSansSuf[nomSansSuf.rfind("/")+1:] - texteSTD=re.sub('XXXXXX',nomSansSuf,texteSTD) - #print texteSTD - f=open(fileSTD,'w') - f.write(texteSTD) - f.close() - except: - print "Pb sauvegarde openturns pour le format STD" - if self.appli.salome == 1: - ok, msg = self.appli.addJdcInSalome( fileSTD ) - ok, msg = self.appli.addJdcInSalome( fileXML ) - -# --------------------------------------------------------------------------- -# Methodes liees aux mots-cles inconnus -# --------------------------------------------------------------------------- - - def mc_inconnus(self): - l_mc = self.JDCDisplay_courant.jdc.get_liste_mc_inconnus() - o = fenetre_mc_inconnus(l_mc) - l = o.wait_new_list() - #print "mc_inconnus_new_list: ",l - #CCAR: Il n' y a pas de retour vers le JDC - - def aideEFICAS(self,event=None): - AIDE.go(master=self.parent) - - def update_jdc_courant(self): - self.JDCDisplay_courant.update() - - def TraduitFichier(self,event=None): - directory = self.appli.CONFIGURATION.rep_user - FichieraTraduire = askopenfilename(title="Nom du Fichier a Traduire", - defaultextension=".comm", - initialdir = directory - ) - if (FichieraTraduire == "" or FichieraTraduire == () ) : return - i=FichieraTraduire.rfind(".") - Feuille=FichieraTraduire[0:i] - FichierTraduit=Feuille+"v8.comm" - log=self.initialdir+"/convert.log" - os.system("rm -rf "+log) - os.system("rm -rf "+FichierTraduit) - Pmw.showbusycursor() - traduitV7V8.traduc(FichieraTraduire,FichierTraduit,log) - Pmw.hidebusycursor() - Entete="Fichier Traduit : "+FichierTraduit +"\n\n" - titre = "conversion de "+ FichieraTraduire - - if os.stat(log)[6] != 0L : - f=open(log) - texte_cr= f.read() - f.close() - else : - texte_cr = Entete - commande="diff "+FichieraTraduire+" "+FichierTraduit+" >/dev/null" - try : - if os.system(commande) == 0 : - texte_cr = texte_cr + "Pas de difference entre le fichier V7 et le fichier traduit" - except : - pass - - cptrendu = FenetreSurLigneWarning(self.appli,titre=titre,texte=texte_cr) - diff --git a/InterfaceTK/catabrowser.py b/InterfaceTK/catabrowser.py deleted file mode 100644 index a4ec7ff1..00000000 --- a/InterfaceTK/catabrowser.py +++ /dev/null @@ -1,398 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -# Modules Python -import os -import sys -import types -import string -import Pmw -from Tkinter import * - -# Modules Eficas -import fontes -from treewidget import Tree -from Editeur.Objecttreeitem import TreeItem -from Accas import AsException -from Noyau.N_CR import justify_text -from Accas import OPER,PROC,MACRO,FORM -from Accas import FACT,BLOC,SIMP - -# -__version__="$Name: BR_dev_V1_13 $" -__Id__="$Id: catabrowser.py,v 1.1.4.2 2007-10-23 09:07:33 pnoyret Exp $" -# -class Tableau: - incr = 10 - def __init__(self,parent,colonnes): - self.parent = parent - self.colonnes = colonnes - self.init() - - def init(self): - # recherche du nombre maxi de lignes et de colonnes.... - for col in self.colonnes : - nb_l = 0 - if len(col) > nb_l : nb_l = len(col) - self.nb_lignes = nb_l - self.nb_colonnes = len(self.colonnes) - # initialisation des coordonnées dans le canvas - self.x0 = self.incr - self.y0 = self.incr - self.x = self.x0 + self.incr - self.y = self.y0 + self.incr - - def affiche(self): - self.scrolledcanvas=Pmw.ScrolledCanvas(self.parent, - hull_width=1., - hull_height=1., - borderframe=1) - Pmw.Color.changecolor(self.scrolledcanvas.component('canvas'),background='gray95') - self.scrolledcanvas.pack(padx=10,pady=10,expand=1, fill="both") - self.canvas = self.scrolledcanvas.component('canvas') - self.affiche_colonnes() - - def affiche_colonnes(self): - for i in range(self.nb_lignes): - self.affiche_ligne(i) - self.aligne_colonnes() - self.trace_traits() - self.scrolledcanvas.resizescrollregion() - - def get_xy_max(self): - try: - x0,y0,xmax,ymax = self.canvas.bbox(ALL) - return xmax,ymax - except: - return None,None - - def trace_traits(self): - xmax,ymax = self.get_xy_max() - if not xmax : return - xmax = xmax+self.incr - ymax = ymax+self.incr - # trace les traits horizontaux - for i in range(self.nb_lignes): - tag_lig = 'ligne_'+`i` - l_id = self.canvas.find_withtag(tag_lig) - x0,y0,x1,y1 = self.bbox(l_id) - self.canvas.create_line(x0-self.incr,y0-self.incr,xmax,y0-self.incr) - self.canvas.create_line(self.x0,ymax,xmax,ymax) - # trace les traits verticaux - for j in range(self.nb_colonnes): - tag_col = 'colonne_'+`j` - l_id = self.canvas.find_withtag(tag_col) - x0,y0,x1,y1 = self.bbox(l_id) - self.canvas.create_line(x0-self.incr,y0-self.incr,x0-self.incr,ymax) - self.canvas.create_line(xmax,self.y0,xmax,ymax) - - def bbox(self,l_id): - x0,y0,x1,y1 = self.canvas.bbox(l_id[0]) - for id in l_id[1:]: - x2,y2,x3,y3 = self.canvas.bbox(id) - x0 = min(x2,x0) - y0 = min(y2,y0) - x1 = max(x3,x1) - y1 = max(y3,y1) - return x0,y0,x1,y1 - - def affiche_ligne(self,num_lig): - tag_lig = 'ligne_'+`num_lig` - num_col = 0 - for col in self.colonnes: - tag_col = 'colonne_'+`num_col` - x = 100*num_col+self.x - id = self.canvas.create_text(x,self.y, - text = justify_text(col[num_lig],cesure=60), - tag=(tag_lig,tag_col), - anchor='nw', - font = fontes.canvas) - x0,y0,x1,y1 = self.canvas.bbox(id) - num_col = num_col+1 - l_id = self.canvas.find_withtag(tag_lig) - x0,y0,x1,y1 = self.bbox(l_id) - self.y = y1 + 2*self.incr - - def aligne_colonnes(self): - num_col = 0 - for col in self.colonnes: - tag_col = 'colonne_'+`num_col` - l_id = self.canvas.find_withtag(tag_col) - if not l_id : continue - x0,y0,x1,y1 = self.bbox(l_id) - self.move(x1+self.incr,self.colonnes[num_col+1:],num_col+1) - num_col = num_col+1 - - def move(self,x,colonnes,num): - num_col = num - for col in colonnes: - tag_col = 'colonne_'+`num_col` - l_id = self.canvas.find_withtag(tag_col) - if not l_id : continue - x0,y0,x1,y1 = self.canvas.bbox(l_id[0]) - self.canvas.move(tag_col,x+self.incr-x0,0) - num_col = num_col+1 - -class CATAPanel(Frame) : - """ Classe servant à créer le panneau représentant l'objet sélectionné dans l'arbre""" - def __init__(self,parent,panneau,node) : - self.parent=parent - self.panneau = panneau - self.node=node - Frame.__init__(self,self.panneau) - self.place(x=0,y=0,relheight=1,relwidth=1) - self.init() - - def init(self): - # création du label initial - label = Label(self, - text = 'Attributs de '+self.node.item.labeltext, - font = fontes.standard_gras_souligne) - label.pack(side='top',pady=10) - # création des listes correspondant aux colonnes du tableau à afficher - colonne1,colonne2 = self.get_listes() - # affichage du tableau - self.tableau = Tableau(self,(colonne1,colonne2)) - self.tableau.affiche() - - def get_listes(self): - self.node.item.get_dico_attributs() - l_cles_attributs = self.node.item.d_attributs.keys() - l_cles_attributs.sort() - ind=0 - liste1 = [] - liste2=[] - for nom_attr in l_cles_attributs : - valeur = self.node.item.d_attributs[nom_attr] - if type(valeur) == types.TupleType: - texte ='' - for elem in valeur: - if type(elem) == types.ClassType: - texte = texte + elem.__name__ - else: - texte = texte + str(elem) - elif type(valeur) == types.ClassType : - texte = valeur.__name__ - else: - texte = str(valeur) - liste1.append(nom_attr) - liste2.append(texte) - return liste1,liste2 - -class CATAItem(TreeItem): - panel = CATAPanel - def __init__(self,appli,labeltext,object,setfunction=None,objet_cata_ordonne = None): - self.appli = appli - self.labeltext = labeltext - self.object=object - self.setfunction = setfunction - self.objet_cata_ordonne = objet_cata_ordonne - - def get_dico_fils(self): - d_fils = {} - if type(self.object) != types.TupleType: - for e in dir(self.object): - cmd = getattr(self.object,e) - if isCMD(cmd) : - d_fils[string.strip(cmd.nom)] = cmd - else: - for obj in self.object : - for e in dir(obj): - cmd = getattr(obj,e) - if isCMD(cmd) : - d_fils[string.strip(cmd.nom)] = cmd - self.d_fils = d_fils - - def get_dico_attributs(self): - d_attributs ={} - if type(self.object) == types.TupleType : - self.d_attributs = d_attributs - return - l_noms_attributs = ['nom','op','sd_prod','reentrant','repetable','fr','docu','into','valide_vide','actif', - 'regles','op_init','niveau','definition','code','niveaux','statut', - 'defaut','min','max','homo','position','val_min','val_max','condition'] - for nom_attribut in l_noms_attributs : - if hasattr(self.object,nom_attribut): - attr = getattr(self.object,nom_attribut) - d_attributs[nom_attribut] = attr - self.d_attributs = d_attributs - - def get_liste_mc_ordonnee(self): - """ Retourne la liste ordonnée (suivant le catalogue) brute des fils - de l'entite courante """ - if hasattr(self.objet_cata_ordonne,'ordre_mc'): - return self.objet_cata_ordonne.ordre_mc - else : - l=self.objet_cata_ordonne.keys() - l.sort() - return l - - def GetLabelText(self): - return self.labeltext,None,None - - def get_fr(self): - return '' - - def isMCList(self): - return 0 - - def GetSubList(self): - sublist=[] - if not hasattr(self,'d_fils'): - self.get_dico_fils() - # on classe les fils dans l'odre du catalogue ... - l_cles_fils = self.get_liste_mc_ordonnee() - for k in l_cles_fils : - if type(self.objet_cata_ordonne) == types.InstanceType : - objet_cata = self.objet_cata_ordonne.entites[k] - else : - objet_cata = self.objet_cata_ordonne.get(k,None) - item = make_objecttreeitem(self.appli,k + " : ",self.d_fils[k], - objet_cata_ordonne = objet_cata) - sublist.append(item) - return sublist - - def GetIconName(self): - return 'ast-green-square' - - def isactif(self): - return 1 - -class CMDItem(CATAItem): - - def get_dico_fils(self): - self.d_fils = self.object.entites - -class SIMPItem(CATAItem): - d_fils={} - d_attributs={} - - def GetIconName(self): - return 'ast-green-ball' - - def IsExpandable(self): - return 0 - -class FACTItem(CMDItem): - def GetIconName(self): - return 'ast-green-los' - -class BLOCItem(FACTItem): pass - -class ATTRIBUTItem(SIMPItem): - def get_dico_attributs(self): - self.d_attributs = {} - - def GetSubList(self): - return [] - - def IsExpandable(self): - return 0 - - def GetText(self): - return self.object - - def GetIconName(self): - return 'aucune' - -class CataBrowser: - def __init__(self,parent,appli,cata,item = None): - self.parent = parent - self.cata = cata - self.appli = appli - self.item = item - self.init() - - def close(self): - self.top.destroy() - - def init(self): - self.nodes={} - self.top = Pmw.Dialog(self.parent, - title = "Visualisation d'un catalogue", - buttons=('OK',), - command = self.quit) - self.pane = Pmw.PanedWidget(self.top.component('dialogchildsite'), - hull_width = 800, - hull_height = 500, - orient = 'horizontal') - self.pane.add('canvas',min = 0.4, max = 0.6, size = 0.5) - self.pane.add('panel',min = 0.4, max = 0.6, size = 0.5) - self.pane.pack(expand =1, fill = 'both') - self.scrolledcanvas = Pmw.ScrolledCanvas(self.pane.pane('canvas'), - hull_width=1., - hull_height=1., - borderframe=1) - Pmw.Color.changecolor(self.scrolledcanvas.component('canvas'),background='gray95') - self.scrolledcanvas.pack(padx=10,pady=10,expand=1, fill="both") - if self.item == None : - self.item = CATAItem(self.appli,"Catalogue",self.cata) - self.tree = Tree(self.appli,self.item,self.scrolledcanvas,command = self.select_node) - self.tree.draw() - self.node = self.tree.node_selected - - def select_node(self,node): - self.nodes[node]=self.create_panel(node) - - def create_panel(self,node): - if hasattr(node.item,"panel"): - return getattr(node.item,"panel")(self,self.pane.pane('panel'),node) - - def quit(self,nom_bouton) : - self.top.destroy() - - def settitle(self): - self.top.wm_title("Browser de catalogue " ) - self.top.wm_iconname("CataBrowser") - - -dispatch = { - OPER : CMDItem, - PROC : CMDItem, - MACRO : CMDItem, - SIMP : SIMPItem, - FACT : FACTItem, - BLOC : BLOCItem, -} - -def TYPE(o): - if isinstance(o,OPER):return OPER - elif isinstance(o,PROC):return PROC - elif isinstance(o,MACRO):return MACRO - elif isinstance(o,FORM):return MACRO - elif isinstance(o,SIMP):return SIMP - elif isinstance(o,FACT):return FACT - elif isinstance(o,BLOC):return BLOC - else:return type(o) - -def make_objecttreeitem(appli,labeltext, object, setfunction=None,objet_cata_ordonne=None): - t = TYPE(object) - if dispatch.has_key(t): - c = dispatch[t] - else: - #print 'on a un objet de type :',t,' ',object - c = ATTRIBUTItem - return c(appli,labeltext, object, setfunction = setfunction,objet_cata_ordonne=objet_cata_ordonne) - -def isCMD(cmd): - return isinstance(cmd,OPER) or isinstance(cmd,PROC) or isinstance(cmd,MACRO) or isinstance(cmd,FORM) - - - diff --git a/InterfaceTK/cataediteur.py b/InterfaceTK/cataediteur.py deleted file mode 100644 index 6203ba77..00000000 --- a/InterfaceTK/cataediteur.py +++ /dev/null @@ -1,975 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -# Modules Python -import os -import sys -import types -import string -import Pmw -from widgets import showinfo -from Tkinter import * - -# Modules Eficas -import fontes -from widgets import * -from treewidget import Tree -from Editeur.Objecttreeitem import TreeItem -from Accas import AsException -from Noyau.N_CR import justify_text - -from Accas import ASSD,GEOM -import definition_cata - -# -__version__="$Name: BR_dev_V1_13 $" -__Id__="$Id: cataediteur.py,v 1.1.4.2 2007-10-23 09:07:33 pnoyret Exp $" -# - -Fonte_Niveau = fontes.canvas_gras_italique - -class Panel(Frame) : - """ Classe servant de classe mère à toutes celles représentant les - panneaux à afficher en fonction de la nature de l'objet en cours - Elle est toujours dérivée.""" - def __init__(self,parent,panneau,node) : - self.parent=parent - self.panneau = panneau - self.node=node - Frame.__init__(self,self.panneau) - self.place(x=0,y=0,relheight=1,relwidth=1) - #self.creer_boutons() - self.init() - - def creer_boutons(self): - """ Méthode créant les boutons se trouvant dans la partie contextuelle d'EFICAS - (à droite sous les onglets ) """ - self.fr_but = Frame(self,height=30) - self.fr_but.pack(side='bottom',fill='x') - self.bouton_com = Button(self.fr_but, - text = 'Commentaire', - command = self.ajout_commentaire, - width=14) - self.bouton_sup = Button(self.fr_but, - text = "Supprimer", - command=self.supprimer, - width=14) - self.bouton_doc = Button(self.fr_but, - text="Documentation", - command=self.visu_doc, - width=14) - self.bouton_cata = Button(self.fr_but, - text = "Catalogue", - command = self.show_catalogue, - width=14) - if self.parent.appli.CONFIGURATION.isdeveloppeur == 'OUI': - self.bouton_sup.place(relx=0.25,rely = 0.5,relheight = 0.8,anchor='w') - self.bouton_cata.place(relx=0.5,rely = 0.5,relheight = 0.8,anchor='w') - self.bouton_doc.place(relx=0.75,rely = 0.5,relheight = 0.8,anchor='w') - else: - self.bouton_sup.place(relx=0.3,rely = 0.5,relheight = 0.8,anchor='w') - self.bouton_doc.place(relx=0.7,rely = 0.5,relheight = 0.8,anchor='w') - - def show_catalogue(self): - try: - genea = self.node.item.get_genealogie() - self.parent.appli.browser_catalogue_objet(genea) - except Exception,e: - traceback.print_exc() - - def efface(self): - self.node.efface() - - def ajout_commentaire(self,ind='after'): - """ Ajoute un commentaire à l'intérieur du JDC, par défaut après le noeud en cours""" - if self.parent.modified == 'n' : self.parent.init_modif() - return self.node.append_brother("COMMENTAIRE",ind) - - def ajout_commentaire_first(self): - """ Ajoute un commentaire en début de JDC""" - if self.parent.modified == 'n' : self.parent.init_modif() - return self.node.append_child("COMMENTAIRE",'first') - - def visu_doc(self): - """ Permet d'ouvrir le fichier doc U de la commande au format pdf avec Acrobat Reader - - Ne fonctionne pas sous UNIX (chemin d'accès Acrobat Reader) - - indication du chemin d'accès aux fichiers pdf à revoir : trop statique""" - cle_doc = self.parent.appli.get_docu(self.node) - if cle_doc == None : return - cle_doc = string.replace(cle_doc,'.','') - commande = self.parent.appli.CONFIGURATION.exec_acrobat - nom_fichier = cle_doc+".doc" - rep_fichier = cle_doc[0:2] - fichier = os.path.abspath(os.path.join(self.parent.appli.CONFIGURATION.path_doc,rep_fichier,nom_fichier)) - print 'commande =',commande - print 'fichier =',fichier - print 'existe =',os.path.isfile(fichier) - if os.name == 'nt': - os.spawnv(os.P_NOWAIT,commande,(commande,fichier)) - elif os.name == 'posix': - script ="#!/usr/bin/sh \n%s %s" %(commande,nom_fichier) - pid = os.system(script) - - def supprimer(self): - """ Suppression du noeud courant """ - if self.parent.modified == 'n' : self.parent.init_modif() - pere = self.node.parent - self.node.delete() - pere.select() - - def affiche(self): - """ Force l'affichage des fenêtres en cours """ - self.tkraise() - - def selectMC(self,name): - """ On retrouve le mot-clé sous le curseur pour affichage du fr """ - cmd=self.node.item.get_definition() - texte_infos = '' - for e in cmd.entites.keys() : - if e == name : - texte_infos=getattr(cmd.entites[e],'fr') - break - if texte_infos == '' : texte_infos="Pas d'infos disponibles" - self.parent.appli.affiche_infos(texte_infos) - - def defMC(self,name): - """ On ajoute un mot-clé à la commande : subnode """ - if name == SEPARATEUR:return - if self.parent.modified == 'n' : self.parent.init_modif() - if name != "COMMENTAIRE": - self.node.append_child(name) - else : - self.ajout_commentaire() - - def selectFilsCmd(self,name): - pass - - def defFilsCmd(self,name): - pass - - def defCmdFirst(self,name): - """ On ajoute une commande ou un commentaire au début du fichier de commandes """ - if name == SEPARATEUR:return - if self.parent.modified == 'n' : self.parent.init_modif() - if name != "COMMENTAIRE": - new_node = self.node.append_child(name,'first') - else : - new_node = self.ajout_commentaire_first() - - def add_commande_avant(self,event=None): - pass - - def add_commande_apres(self,event=None): - pass - -class OngletPanel(Panel) : - """ Cette classe est virtuelle et doit être dérivée - Elle contient les principales méthodes d'affichage des différents onglets""" - - def raisecmd(self,page): - self.nb.page(page).focus_set() - if page == 'Concept': self._any.focus() - - def affiche(self): - page=self.nb.getcurselection() - self.nb.page(page).focus_set() - if page == 'Concept':self._any.component('entry').focus_set() - self.tkraise() - - def makeConceptPage(self,page): - """ Crée la page de saisie du nom du concept """ - self.label = Label(page,text='Nom du concept :') - self.label.place(relx=0.1,rely=0.4) - self._any = Entry(page,relief='sunken') - self._any.place(relx=0.35,rely=0.4,relwidth=0.5) - self._any.bind("",lambda e,s=self:s.execConcept()) - self._any.bind("",lambda e,s=self:s.execConcept()) - self._any.insert(0,self.node.item.GetText()) - type_sd = self.node.item.object.get_type_sd_prod() - if type_sd : - txt = "L'opérateur courant retourne un objet de type %s" %type_sd - self.label = Label(page, text = txt) - self.label.place(relx=0.5,rely=0.55,anchor='n') - self._any.focus() - - def makeCommandePage(self,page): - """ Affiche la page d'ajout d'une commande relativement à l'objet commande sélectionné """ - titre = "Où voulez-vous insérer une commande par rapport à %s" %self.node.item.object.nom - Label(page,text=titre).place(relx=0.5,rely=0.2,anchor='w') - b_avant = Button(page,text='AVANT', - command = self.node.item.add_commande_avant) - b_apres = Button(page,text='APRES', - command = self.node.item.add_commande_apres) - b_avant.place(relx=0.35,rely=0.5,anchor='w') - b_apres.place(relx=0.65,rely=0.5,anchor='w') - - def deselectMC(self,name): - self.parent.appli.affiche_infos('') - - def get_liste_cmd(self): - listeCmd = self.node.item.object.niveau.definition.get_liste_cmd() - return listeCmd - - def get_liste_fils_cmd(self): - return ['Mot-clé simple','Mot-clé facteur','Bloc'] - - def makeMoclesPage(self,page): - frame1 = Frame(page,height = 20) - frame1.pack(side='top',fill='x') - label = Label(frame1,text ="Le mot-clé choisi sera ajouté à la fin du catalogue") - label.pack(side='top') - frame2 = Frame(page) - frame2.pack(side='top',fill='both',expand=1) - liste_cmd = self.get_liste_fils_cmd() - liste_commandes = (("",self.selectFilsCmd), - ("",self.deselectFilsCmd), - ("",self.defFilsCmd)) - Liste = ListeChoix(self,frame2,liste_cmd,liste_commandes = liste_commandes,titre = "Mots-clés") - Liste.affiche_liste() - - def deselectFilsCmd(self,name): - pass - - def makeJDCPage(self,page): - liste_cmd = self.get_liste_cmd() - liste_commandes = (("",self.selectCmd), - ("",self.deselectCmd), - ("",self.defCmdFirst)) - Liste = ListeChoix(self,page,liste_cmd,liste_commandes = liste_commandes,filtre='oui',titre = "Commandes") - Liste.affiche_liste() - - def makeReglesPage(self,page) : - regles = [] - regles = self.node.item.get_regles() - dictionnaire = self.node.item.get_mc_presents() - texte_regles = [] - l_regles_en_defaut=[] - if len(regles) > 0: - i = 0 - for regle in regles : - texte_regles.append(regle.gettext()) - texte,test = regle.verif(dictionnaire) - if test == 0 : l_regles_en_defaut.append(i) - i = i+1 - Liste = ListeChoix(self,page,texte_regles,liste_marques=l_regles_en_defaut,active='non',titre="Règles") - Liste.affiche_liste() - #self.afficheListe(page,texte_regles,self.selectRegle,self.execRegle) - - def execConcept(self): - """ Nomme le concept SD retourné par l'étape """ - if self.parent.modified == 'n' : self.parent.init_modif() - nom = self._any.get() - # Pourquoi node.etape ??? - #test,mess = self.node.etape.item.nomme_sd(nom) - test,mess = self.node.item.nomme_sd(nom) - self.parent.appli.affiche_infos(mess) - self.node.racine.update() - - def changed(self): - pass - - def makeAttributsPage(self,page): - l_attributs=self.node.item.object.attributs - d_defauts = self.node.item.object.attributs_defauts - for attribut in l_attributs : - attr = self.node.item.object.entites_attributs.get(attribut,None) - if attr.valeur is d_defauts[attribut] : - texte = attribut+' = '+repr(attr.valeur)+' (defaut)' - else: - texte = attribut+' = '+repr(attr.valeur) - Label(page,text=texte).pack(side='top') - - def makeSimpPage(self,page): - texte = "Où voulez-vous ajouter un mot-clé simple ?" - Label(page,text=texte).place(relx=0.5,rely=0.3,anchor='center') - b1 = Button(page,text='AVANT '+self.node.item.object.nom,command=self.add_simp_avant) - b2 = Button(page,text='APRES '+self.node.item.object.nom,command=self.add_simp_apres) - b1.place(relx=0.5,rely=0.5,anchor='center') - b2.place(relx=0.5,rely=0.6,anchor='center') - - def add_simp_avant(self,event=None): - """ - Ajoute un mot-clé simple avant celui courant - """ - self.node.append_brother('new_simp','before') - self.node.update() - - def add_simp_apres(self,event=None): - """ - Ajoute un mot-clé simple après celui courant - """ - self.node.append_brother('new_simp','after') - self.node.update() - -class TYPEPanel(Frame): - def __init__(self,parent,panneau,node) : - self.parent=parent - self.panneau = panneau - self.node=node - Frame.__init__(self,self.panneau) - self.place(x=0,y=0,relheight=1,relwidth=1) - self.creer_texte() - - def creer_texte(self): - texte = "Le noeud sélectionné correspond à un type\n" - self.label = Label(self,text=texte) - self.label.place(relx=0.5,rely=0.4,relwidth=0.8,anchor='center') - -class OPERPanel(OngletPanel): - def init(self): - nb = Pmw.NoteBook(self,raisecommand=self.raisecmd) - - nb.pack(fill = 'both', expand = 1) - self.nb=nb - nb.add('Mocles', tab_text='Ajouter mots-clés') - nb.add('Commandes',tab_text='Ajouter une commande') - self.makeMoclesPage(nb.page("Mocles")) - self.makeCommandePage(nb.page("Commandes")) - nb.tab('Mocles').focus_set() - nb.setnaturalsize() - self.affiche() - -class SIMPPanel(OngletPanel): - def init(self): - nb = Pmw.NoteBook(self,raisecommand=self.raisecmd) - nb.pack(fill = 'both', expand = 1) - self.nb=nb - nb.add('generaux', tab_text='Données générales') - nb.add('ihm',tab_text='Données IHM') - nb.add('mocle',tab_text='Ajouter un mot-cle simple') - self.makeAttributsGenerauxPage(nb.page("generaux")) - self.makeAttributsIHMPage(nb.page("ihm")) - self.makeSimpPage(nb.page('mocle')) - nb.tab('generaux').focus_set() - nb.setnaturalsize() - self.affiche() - - def makeAttributsGenerauxPage(self,page): - fr1 = Frame(page,bd=1,relief='raised') - fr2 = Frame(page,bd=1,relief='raised') - fr3 = Frame(page,bd=1,relief='raised') - fr4 = Frame(page,bd=1,relief='raised') - fr5 = Frame(page,bd=1,relief='raised') - fr1.place(relheight=0.14,relwidth=1,rely=0) - fr2.place(relheight=0.14,relwidth=1,rely=0.14) - fr3.place(relheight=0.29,relwidth=1,rely=0.28) - fr4.place(relheight=0.14,relwidth=1,rely=0.57) - fr5.place(relheight=0.28,relwidth=1,rely=0.71) - # nom du mot-clé - Label(fr1,text = 'Nom :').place(relx=0.05,rely=0.3,anchor='w') - self.e_nom = Entry(fr1) - self.e_nom.place(relx=0.35,rely=0.3,relwidth=0.3,anchor='w') - self.e_nom.bind("",lambda e,s=self : s.set_valeur_attribut('nom',None)) - self.e_nom.bind("",lambda e,s=self : s.set_valeur_attribut('nom',None)) - self.e_nom.insert(0,self.get_valeur_attribut('nom')) - # Statut - Label(fr1,text='Statut : ').place(relx=0.05,rely=0.7,anchor='w') - self.statut=StringVar() - valeurs_statut=[('obligatoire','o'), - ('facultatif','f'), - ('caché','c') - ] - self.statut.set(self.node.item.object.get_valeur_attribut('statut')) - i=0 - for text,mode in valeurs_statut: - b=Radiobutton(fr1,text=text,variable=self.statut,value=mode, - command = lambda s=self,m=mode : s.set_valeur_attribut('statut',m)) - b.place(relx=0.25+i*0.25,rely=0.7,anchor='w') - i=i+1 - # Type ... - Label(fr2,text='Type de la valeur : ').place(relx=0.05,rely=0.5,anchor='w') - self.e_type = Entry(fr2) - self.e_type.place(relx=0.35,rely=0.5,relwidth=0.5,anchor='w') - self.e_type.insert(0,self.node.item.object.get_valeur_attribut('type')) - # Domaine de validité - Label(fr3,text='Domaine de validité : ').place(relx=0.05,rely=0.2,anchor='w') - self.domaine = StringVar() - self.domaine.set(self.node.item.object.get_valeur_attribut('domaine_validité')) - b1=Radiobutton(fr3,text='continu',variable=self.domaine,value='continu', - command=lambda s=self,f=fr3 :s.change_domaine(f)) - b2=Radiobutton(fr3,text='discret',variable=self.domaine,value='discret', - command=lambda s=self,f=fr3 :s.change_domaine(f)) - b1.place(relx=0.35,rely=0.2,anchor='w') - b2.place(relx=0.65,rely=0.2,anchor='w') - self.change_domaine(fr3) - # Défaut ... - if self.domaine.get() == 'continu': - # le développeur peut donner la valeur qu'il souhaite, moyennant la vérification de type... - Label(fr4,text='Valeur par défaut : ').place(relx=0.05,rely=0.5,anchor='w') - self.e_defaut = Entry(fr4) - self.e_defaut.place(relx=0.35,rely=0.5,relwidth=0.5,anchor='w') - if self.node.item.object.get_valeur_attribut('defaut') : - self.e_defaut.insert(0,self.node.item.object.get_valeur_attribut('defaut')) - self.e_defaut.bind("",lambda e,s=self : s.set_valeur_attribut('defaut',None)) - self.e_defaut.bind("",lambda e,s=self : s.set_valeur_attribut('defaut',None)) - else : - # dans le cas discret, la valeur par défaut doit être dans l'ensemble des valeurs possibles (into) - liste = self.node.item.object.get_valeur_attribut('into') - if self.node.item.object.get_valeur_attribut('defaut') : - self.set_valeur_attribut('defaut',self.node.item.object.get_valeur_attribut('defaut')) - if liste == None : liste = [] - self.e_defaut = Pmw.OptionMenu(fr4,labelpos='w',label_text = "Valeur par défaut : ", - items = self.node.item.object.get_valeur_attribut('into'), - menubutton_width=30) - self.e_defaut.configure(command = lambda e,s=self : s.set_valeur_attribut('defaut',None)) - self.e_defaut.place(relx=0.05,rely=0.5,anchor='w') - # Liste de valeurs ? - Label(fr5,text='Liste de valeurs : ').place(relx=0.05,rely=0.2,anchor='w') - self.liste_valeurs = BooleanVar() - liste_valeurs = [('OUI',1),('NON',0)] - self.liste_valeurs.set(0) - i=0 - for text,mode in liste_valeurs: - b=Radiobutton(fr5,text=text,variable=self.liste_valeurs,value=mode, - command=lambda s=self,f=fr5 :s.change_liste_valeurs(f)) - b.place(relx=0.35+i*0.2,rely=0.2,anchor='w') - i=i+1 - self.change_liste_valeurs(fr5) - - def makeAttributsIHMPage(self,page): - fr1 = Frame(page,height=100,bd=1,relief='raised') - fr2 = Frame(page,height=50,bd=1,relief='raised') - fr1.pack(side='top',fill='x') - fr2.pack(side='top',fill='x') - # Champ fr ... - Label(fr1,text='Champ fr : ').place(relx=0.05,rely=0.35,anchor='w') - self.e_fr = Entry(fr1) - self.e_fr.place(relx=0.35,rely=0.35,relwidth=0.6,anchor='w') - self.e_fr.insert(0,self.node.item.object.get_valeur_attribut('fr')) - # Champ ang ... - Label(fr1,text='Champ ang : ').place(relx=0.05,rely=0.70,anchor='w') - self.e_ang = Entry(fr1) - self.e_ang.place(relx=0.35,rely=0.70,relwidth=0.6,anchor='w') - self.e_ang.insert(0,self.node.item.object.get_valeur_attribut('ang')) - # Clé documentaire ... - Label(fr2,text='Clé documentaire : ').place(relx=0.05,rely=0.50,anchor='w') - self.e_docu = Entry(fr2) - self.e_docu.place(relx=0.35,rely=0.50,relwidth=0.6,anchor='w') - self.e_docu.insert(0,self.node.item.object.get_valeur_attribut('docu')) - - def detruit_widgets(self,l_widgets): - for nom_widg in l_widgets : - try: - widg = getattr(self,nom_widg) - widg.place_forget() - delattr(self,nom_widg) - except: - pass - - def change_liste_valeurs(self,fr5): - valeur = self.liste_valeurs.get() - if valeur == 0 : - # pas de liste de valeurs - l_widgets=['l_homo','b1_homo','b2_homo','l_min','e_min','l_max','e_max'] - self.detruit_widgets(l_widgets) - elif valeur == 1: - # pas de widgets à détruire ... - if hasattr(self,'l_homo') : - # on est déjà en mode 'liste' --> rien à faire - return - # homo - self.l_homo = Label(fr5,text='Liste homogène : ') - self.l_homo.place(relx=0.05,rely=0.4,anchor='w') - self.homo = BooleanVar() - self.homo.set(self.node.item.object.get_valeur_attribut('homo')) - self.b1_homo=Radiobutton(fr5,text='OUI',variable=self.homo,value=1) - self.b2_homo=Radiobutton(fr5,text='NON',variable=self.homo,value=0) - self.b1_homo.place(relx=0.35,rely=0.4,anchor='w') - self.b2_homo.place(relx=0.65,rely=0.4,anchor='w') - # min ... - self.l_min = Label(fr5,text='Longueur minimale : ') - self.l_min.place(relx=0.05,rely=0.6,anchor='w') - self.e_min = Entry(fr5) - self.e_min.place(relx=0.4,rely=0.6,relwidth=0.3,anchor='w') - self.e_min.insert(0,self.node.item.object.get_valeur_attribut('min')) - # max ... - self.l_max = Label(fr5,text='Longueur maximale : ') - self.l_max.place(relx=0.05,rely=0.8,anchor='w') - self.e_max = Entry(fr5) - self.e_max.place(relx=0.4,rely=0.8,relwidth=0.3,anchor='w') - self.e_max.insert(0,self.node.item.object.get_valeur_attribut('max')) - - def change_domaine(self,fr3): - valeur = self.domaine.get() - if valeur == 'discret' : - l_widgets = ['l_val_min','l_val_max','e_val_min','e_val_max'] - self.detruit_widgets(l_widgets) - # into - #self.l_into = Label(fr3,text='Ensemble de valeurs : ') - #self.l_into.place(relx=0.2,rely=0.5,anchor='w') - self.e_into = Pmw.ScrolledListBox(fr3, - items=self.node.item.object.get_valeur_attribut('into'), - labelpos='w', - label_text= 'Ensemble de valeurs : ', - listbox_height = 3, - dblclickcommand = self.change_into) - self.e_into.place(relx=0.05,rely=0.6,relwidth=0.9,anchor='w') - #self.e_into.insert(0,self.node.item.object.get_valeur_attribut('into')) - elif valeur == 'continu': - l_widgets = ['l_into','e_into'] - self.detruit_widgets(l_widgets) - if hasattr(self,'l_val_min'): - # on est déjà en mode 'continu' --> rien à faire - return - # val_min - self.l_val_min = Label(fr3,text='Valeur minimale : ') - self.l_val_min.place(relx=0.05,rely=0.5,anchor='w') - self.e_val_min = Entry(fr3) - self.e_val_min.place(relx=0.35,rely=0.5,relwidth=0.5,anchor='w') - self.e_val_min.bind("",lambda e,s=self : s.set_valeur_attribut('val_min',None)) - self.e_val_min.bind("",lambda e,s=self : s.set_valeur_attribut('val_min',None)) - self.set_valeur_attribut('val_min',self.get_valeur_attribut('val_min')) - # val_max - self.l_val_max = Label(fr3,text='Valeur maximale : ') - self.l_val_max.place(relx=0.05,rely=0.8,anchor='w') - self.e_val_max = Entry(fr3) - self.e_val_max.place(relx=0.35,rely=0.8,relwidth=0.5,anchor='w') - self.e_val_max.bind("",lambda e,s=self : s.set_valeur_attribut('val_max',None)) - self.e_val_max.bind("",lambda e,s=self : s.set_valeur_attribut('val_max',None)) - self.set_valeur_attribut('val_max',self.get_valeur_attribut('val_max')) - -# ------------------------------------------------------------------ -# Méthodes de validation des entrées faites par l'utilisateur -# ------------------------------------------------------------------ - - def get_valeur_attribut(self,nom_attr): - """ - Demande à l'item de retourner la valeur de l'attribut nom_attr - """ - return self.node.item.get_valeur_attribut(nom_attr) - - def set_valeur_attribut(self,nom_attr,new_valeur): - """ - Affecte la valeur new_valeur à l'attribut nom_attr - Vérifie si celle-ci est valide, sinon restaure l'ancienne - """ - if new_valeur is None : - widget = getattr(self,'e_'+nom_attr) - if hasattr(widget,'getcurselection'): - new_valeur = widget.getcurselection() - else: - new_valeur = widget.get() - print "on affecte %s a %s" %(str(new_valeur),nom_attr) - self.node.item.set_valeur_attribut(nom_attr,new_valeur) - self.node.update() - - def change_into(self): - """ - Méthode activée par double clic sur la ListBox d'affichage des valeurs discrètes possibles : - permet de changer la liste de ces valeurs - """ - showinfo("Fonction non encore disponible", - "Vous ne pouvez pas encore modifier la liste into par cette IHM") - -class OBJECTItem(TreeItem): - def __init__(self,appli,labeltext,object,setfunction=None,objet_cata_ordonne = None): - self.appli = appli - self.labeltext = labeltext - self.object=object - self.setfunction = setfunction - self.objet_cata_ordonne = objet_cata_ordonne - - def GetLabelText(self): - return self.labeltext,None,None - - def get_fr(self): - return '' - - def isMCList(self): - return 0 - - def isactif(self): - return 1 - - def add_commande_avant(self): - pass - - def add_commande_apres(self): - pass - - def set_valeur_attribut(self,nom_attr,new_valeur): - """ - Affecte la valeur new_valeur à l'attribut nom_attr - Vérifie si celle-ci est valide, sinon restaure l'ancienne - """ - old_valeur = self.object.get_valeur_attribut(nom_attr) - self.object.set_valeur_attribut(nom_attr,new_valeur) - verificateur = 'verif_'+nom_attr - if hasattr(self.object,verificateur): - if not getattr(self.object,verificateur)(): - # la nouvelle valeur de nom_attr n'est pas valide : on restaure l'ancienne (sans vérification) - self.object.set_valeur_attribut(nom_attr,old_valeur) - print 'changement de valeur refuse' - return - print 'changement de valeur accepte' - self.object.init_modif() - - def get_valeur_attribut(self,nom_attr): - """ - Retourne la valeur de l'attribut nom_attr - """ - return self.object.get_valeur_attribut(nom_attr) - -class CATAItem(OBJECTItem): - def GetSubList(self): - sublist=[] - for fils in self.object.entites_fils: - item = make_objecttreeitem(self.appli,fils.objet.label + " : ",fils,objet_cata_ordonne=self.objet_cata_ordonne) - sublist.append(item) - return sublist - - def GetIconName(self): - if self.object.isvalid(): - return 'ast-green-square' - else: - return 'ast-red-square' - - def GetText(self): - return "Catalogue %s" %self.appli.code - - def add_commande_avant(self): - pass - - def add_commande_apres(self): - pass - - -def transforme_liste_dico(liste): - d={} - for item in liste : - d[item.nom]=item - return d - -class OPERItem(OBJECTItem): - panel = OPERPanel - def GetSubList(self): - sublist=[] - # on classe les fils dans l'ordre du catalogue ... - l_cles_fils = self.get_liste_mc_ordonnee() - # on crée les items fils ... - dico_fils = transforme_liste_dico(self.object.entites_fils) - for k in l_cles_fils : - typ = TYPE_COMPLET(dico_fils[k]) - if type(self.objet_cata_ordonne) == types.InstanceType : - objet_cata = self.objet_cata_ordonne.entites[k] - else : - objet_cata = self.objet_cata_ordonne.get(k,None) - item = make_objecttreeitem(self.appli,typ + " : ",dico_fils[k],objet_cata_ordonne = objet_cata) - sublist.append(item) - return sublist - - def GetText(self): - #return self.object.nom - return self.object.get_valeur_attribut('nom') - - def get_liste_mc_ordonnee(self): - return self.objet_cata_ordonne.ordre_mc - - def GetIconName(self): - if self.object.isvalid(): - return 'ast-green-square' - else: - return 'ast-red-square' - - def additem(self,name,pos): - if isinstance(name,TreeItem) : - cmd=self.object.addentite(name.getObject(),pos) - else : - cmd = self.object.addentite(name,pos) - typ = TYPE_COMPLET(cmd) - item = make_objecttreeitem(self.appli,typ + " : ", cmd) - return item - - def get_attribut(self,nom): - if nom == 'nature': return 'OPERATEUR' - - def get_liste_mc_presents(self): - return [] - - def verif_condition_regles(self,liste): - return [] - -class PROCItem(OPERItem): - panel = OPERPanel - -class MACROItem(OPERItem): - panel = OPERPanel - -class SIMPItem(OPERItem): - panel = SIMPPanel - - def GetIconName(self): - if self.object.isvalid(): - return 'ast-green-ball' - else: - return 'ast-red-ball' - - def IsExpandable(self): - return 0 - - def GetSubList(self): - return [] - -class FACTItem(OPERItem): - def GetIconName(self): - if self.object.isvalid(): - return 'ast-green-los' - else: - return 'ast-red-los' - -class BLOCItem(FACTItem): pass - -class TYPEItem(SIMPItem): - panel = TYPEPanel - def get_dico_attributs(self): - self.d_attributs = {} - - def GetSubList(self): - return [] - - def IsExpandable(self): - return 0 - - def GetText(self): - return self.object.nom - -class NIVEAUItem(OPERItem): - def IsExpandable(self): - return 1 - - def get_liste_mc_ordonnee(self): - l=[] - for fils in self.object.entites_fils: - l.append(fils.nom) - return l - - def GetSubList(self): - sublist=[] - # on classe les fils dans l'ordre du catalogue ... - l_cles_fils = self.get_liste_mc_ordonnee() - # on crꥠles items fils ... - dico_fils = transforme_liste_dico(self.object.entites_fils) - for k in l_cles_fils : - typ = TYPE_COMPLET(dico_fils[k]) - if type(self.objet_cata_ordonne) == types.InstanceType : - objet_cata = self.objet_cata_ordonne.entites[k] - else : - objet_cata = self.objet_cata_ordonne.get(k,None) - item = make_objecttreeitem(self.appli,typ + " : ",dico_fils[k],objet_cata_ordonne = objet_cata) - sublist.append(item) - return sublist - - def GetLabelText(self): - """ Retourne 3 valeurs : - - le texte à afficher dans le noeud représentant l'item - - la fonte dans laquelle afficher ce texte - - la couleur du texte - """ - return self.labeltext,Fonte_Niveau,'#00008b' - - def GetIconName(self): - if self.object.isvalid(): - return "ast-green-text" - else: - return 'ast-red-text' - - def additem(self,name,pos): - if isinstance(name,TreeItem) : - cmd=self.object.addentite(name.getObject(),pos) - else : - cmd = self.object.addentite(name,pos) - typ = TYPE_COMPLET(obj) - item = make_objecttreeitem(self.appli,typ+ " : ", cmd) - return item - - def suppitem(self,item) : - # item = item de l'ETAPE à supprimer du JDC - # item.getObject() = ETAPE ou _C - # self.object = JDC - itemobject=item.getObject() - if self.object.suppentite(itemobject): - if isinstance(itemobject,_C): - message = "Commentaire supprimé" - else : - message = "Commande " + itemobject.nom + " supprimée" - self.appli.affiche_infos(message) - return 1 - else: - self.appli.affiche_infos("Pb interne : impossible de supprimer cet objet") - return 0 - - def GetText(self): - return '' - -class ATTRIBUTItem(SIMPItem): - def get_dico_attributs(self): - self.d_attributs = {} - - def GetSubList(self): - return [] - - def IsExpandable(self): - return 0 - - def GetText(self): - return self.object - - def GetIconName(self): - return 'aucune' - -class CataEditeur: - def __init__(self,parent,appli,cata): - self.parent = parent - self.cata = definition_cata.CATALOGUE(cata) - self.appli = appli - self.top = Toplevel() - self.top.geometry("800x500") - self.top.title("Edition d'un catalogue") - self.init() - - def close(self): - self.top.destroy() - - def init(self): - self.nodes={} - self.creerbarremenus() - self.pane = Pmw.PanedWidget(self.top, - hull_width = 800, - hull_height = 500, - orient = 'horizontal') - self.pane.add('canvas',min = 0.4, max = 0.6, size = 0.45) - self.pane.add('panel',min = 0.4, max = 0.6, size = 0.55) - self.pane.pack(expand =1, fill = 'both') - self.scrolledcanvas = Pmw.ScrolledCanvas(self.pane.pane('canvas'), - hull_width=1., - hull_height=1., - borderframe=1) - Pmw.Color.changecolor(self.scrolledcanvas.component('canvas'),background='gray95') - self.scrolledcanvas.pack(padx=10,pady=10,expand=1, fill="both") - self.item = CATAItem(self.appli,"Catalogue", - self.cata, - objet_cata_ordonne = self.appli.readercata.cata_ordonne_dico) - - self.tree = Tree(self.appli,self.item,self.scrolledcanvas,command = self.select_node) - self.tree.draw() - self.node = self.tree.node_selected - - def creerbarremenus(self) : - self.menubar=Menu(self.top) - self.filemenu=Menu(self.menubar,tearoff=0) - self.filemenu.add_command(label='Quitter',command=self.quit) - - self.editmenu=Menu(self.menubar,tearoff=0) - #self.editmenu.add_command(label='Copier',command=self.copy) - #self.editmenu.add_command(label='Couper',command=self.cut) - #self.editmenu.add_command(label='Coller',command=self.paste) - - self.affichagemenu=Menu(self.menubar,tearoff=0) - self.affichagemenu.add_command(label='Rapport de validation', - command = self.visuCR) - self.affichagemenu.add_command(label='shell',command = self.shell) - #self.affichagemenu.add_command(label='Fichier à¡°lat',command=self.visu_a_plat) - #self.affichagemenu.add_command(label='Fichier .py',command =self.visuJDC_py) - #self.affichagemenu.add_command(label='Fichier source',command = self.visu_txt_brut_JDC) - #self.affichagemenu.add_command(label='Paraméµ²es Eficas',command=self.affichage_fichier_ini) - - #self.optionmenu=Menu(self.menubar,tearoff=0) - #self.optionmenu.add_command(label='Catalogue dê·¥loppeur',command=self.choix_cata_developpeur) - - self.menubar.add_cascade(label='Fichier',menu=self.filemenu) - self.menubar.add_cascade(label='Edition',menu=self.editmenu) - self.menubar.add_cascade(label='Jeu de commandes',menu=self.affichagemenu) - #self.menubar.add_cascade(label='Browsers',menu=self.browsermenu) - #self.menubar.add_cascade(label='Catalogue',menu=self.cataloguemenu) - #self.menubar.add_cascade(label='Options',menu=self.optionmenu) - self.top.configure(menu=self.menubar) - self.top.protocol("WM_DELETE_WINDOW",self.quit) - self.top.minsize(900,500) - self.top.geometry("900x500") - - def shell(self,event=None): - import Interp - d={'j':self.tree.item.getObject()} - Interp.InterpWindow(d,parent=self.parent) - - def visuCR(self,mode='Cata'): - txt = str(self.cata.report()) - titre="Rapport de validation du catalogue" - Fenetre(self.appli,titre=titre,texte=txt) - - def select_node(self,node): - self.nodes[node]=self.create_panel(node) - - def create_panel(self,node): - if hasattr(node.item,"panel"): - return getattr(node.item,"panel")(self,self.pane.pane('panel'),node) - - def quit(self) : - self.top.destroy() - - def settitle(self): - self.top.wm_title("Browser de catalogue " ) - self.top.wm_iconname("CataBrowser") - - -dispatch = { - 'OPER' : OPERItem, - 'PROC' : PROCItem, - 'MACRO' : MACROItem, - 'SIMP' : SIMPItem, - 'FACT' : FACTItem, - 'BLOC' : BLOCItem, - 'TYPE' : TYPEItem, - 'NIVEAU' : NIVEAUItem -} - -def TYPE(o): - if isinstance(o,definition_cata.OPER_CATA):return 'OPER' - elif isinstance(o,definition_cata.PROC_CATA):return 'PROC' - elif isinstance(o,definition_cata.MACRO_CATA):return 'MACRO' - elif isinstance(o,definition_cata.SIMP_CATA):return 'SIMP' - elif isinstance(o,definition_cata.FACT_CATA):return 'FACT' - elif isinstance(o,definition_cata.BLOC_CATA):return 'BLOC' - elif isinstance(o,definition_cata.TYPE_CATA):return 'TYPE' - elif isinstance(o,definition_cata.NIVEAU_CATA) : return 'NIVEAU' - else:return type(o) - -def TYPE_COMPLET(o): - if isinstance(o,definition_cata.OPER_CATA):return "OPERATEUR" - elif isinstance(o,definition_cata.PROC_CATA):return "PROCEDURE" - elif isinstance(o,definition_cata.MACRO_CATA):return "MACRO" - elif isinstance(o,definition_cata.SIMP_CATA):return "Mot-clé SIMPLE" - elif isinstance(o,definition_cata.FACT_CATA):return "Mot-clé FACTEUR" - elif isinstance(o,definition_cata.BLOC_CATA):return "BLOC" - elif isinstance(o,definition_cata.TYPE_CATA):return "Type" - elif isinstance(o,definition_cata.NIVEAU_CATA):return "Niveau" - else: return "Inconnu ("+`type(o)`+")" - -def make_objecttreeitem(appli,labeltext, object, setfunction=None,objet_cata_ordonne=None): - t = TYPE(object) - if dispatch.has_key(t): - c = dispatch[t] - else: - print 'on a un objet de type :',type(object),' ',object - c = ATTRIBUTItem - return c(appli,labeltext, object, setfunction = setfunction,objet_cata_ordonne=objet_cata_ordonne) - - - diff --git a/InterfaceTK/centerwindow.py b/InterfaceTK/centerwindow.py deleted file mode 100644 index 4acca2e4..00000000 --- a/InterfaceTK/centerwindow.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -""" - Ce module contient la fonction utilitaire centerwindow - qui sert à centrer une fenetre -""" -import types - -def centerwindow(window,parent = 'avec'): - if parent =='avec': - parent = window.winfo_parent() - if type(parent) == types.StringType: - parent = window._nametowidget(parent) - # Find size of window. - window.update_idletasks() - width = window.winfo_width() - height = window.winfo_height() - if width == 1 and height == 1: - # If the window has not yet been displayed, its size is - # reported as 1x1, so use requested size. - width = window.winfo_reqwidth() - height = window.winfo_reqheight() - # Place in centre of screen: - if parent =='avec' : - x = (window.winfo_screenwidth() - width) / 2 - parent.winfo_vrootx() - y = (window.winfo_screenheight() - height) / 3 - parent.winfo_vrooty() - else: - x = (window.winfo_screenwidth() - width) / 2 - y = (window.winfo_screenheight() - height) / 3 - if x < 0: - x = 0 - if y < 0: - y = 0 - window.geometry('+%d+%d' % (x, y)) - diff --git a/InterfaceTK/change_comm.py b/InterfaceTK/change_comm.py deleted file mode 100755 index 5fb53226..00000000 --- a/InterfaceTK/change_comm.py +++ /dev/null @@ -1,166 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -""" - Ce module permet de lancer l'application EFICAS en affichant - un ecran Splash pour faire patentier l'utilisateur -""" -# Modules Python -import sys -import os - -# Modules Eficas -from Editeur import import_code -from Editeur import session -import prefs -import convert -import generator -import string -from Editeur.utils import extension_fichier,stripPath, save_in_file - -class DUP : - - def __init__(self,code): - """ - """ - self.format_fichier="python" - self.version_code=None - self.code=code - - self.top=None - self.test=2 - from Editeur import configuration - self.CONFIGURATION=configuration.make_config(self,prefs.REPINI) - - self.load_readercata() - self.cata=self.readercata.cata - - self.JDC=None - self.JDCName="" - self.J2=None - - def load_readercata(self): - mname='readercata' - module=__import__(mname,globals(),locals()) - factory=getattr(module,mname.upper()) - appli_composant=factory(self,self.top) - setattr(self,mname,appli_composant) - - - def openJDC(self,fichier): - if fichier : - self.fichier = fichier - e=extension_fichier(fichier) - self.JDCName=stripPath(fichier) - self.initialdir = os.path.dirname(os.path.abspath(fichier)) - else : - return - - format=self.format_fichier - # Il faut convertir le contenu du fichier en fonction du format - if convert.plugins.has_key(format): - # Le convertisseur existe on l'utilise - p=convert.plugins[format]() - p.readfile(fichier) - text=p.convert('exec',self) - if not p.cr.estvide(): - print ("Erreur à la conversion") - print str(p.cr) - return - - # On se met dans le repertoire ou se trouve le fichier de commandes - # pour trouver les eventuels fichiers include ou autres - # localises a cote du fichier de commandes - os.chdir(self.initialdir) - CONTEXT.unset_current_step() - J=self.cata[0].JdC(procedure=text,appli=self, - cata=self.cata,cata_ord_dico=self.readercata.cata_ordonne_dico, - nom = self.JDCName, - rep_mat=self.CONFIGURATION.rep_mat, - ) - - J.analyse() - - txt_exception = J.cr.get_mess_exception() - if txt_exception : - # des exceptions ont été levées à la création du JDC - # --> on affiche les erreurs mais pas le JDC - self.JDC=J - print("Erreur fatale au chargement de %s" %file) - else : - self.JDC=J - - def modifieJDC(self,texte): - if texte == None or texte == "" : return - format="python" - lignes=string.split(texte,";") - textedecoup="" - for l in lignes : - textedecoup=textedecoup+l+'\n' - if convert.plugins.has_key(format): - p=convert.plugins[format]() - p.settext(textedecoup) - text=p.convert('exec',self) - if not p.cr.estvide(): - print ("Erreur à la conversion") - print str(p.cr) - return - self.J2=self.cata[0].JdC(procedure=text,appli=self, - cata=self.cata, - cata_ord_dico=self.readercata.cata_ordonne_dico, - nom = self.JDCName+"2", - rep_mat=self.CONFIGURATION.rep_mat, - ) - self.J2.definition.code = "MODIF" - self.J2.analyse() - - - def saveJDC(self,fichierSortie): - """ - Sauvegarde le JDC courant. - Retourne 1 si la sauvegarde s'est bien faite, 0 sinon. - """ - if not hasattr(self,'JDC') : return 0 - - format="Modif" - - if generator.plugins.has_key(format): - g=generator.plugins[format]() - jdc_formate=g.genermodifparam(self.JDC,self.J2) - if not g.cr.estvide(): - self.affiche_infos("Erreur à la generation") - return 0 - else: - self.affiche_infos("Format %s non reconnu" % format) - return 0 - - self.jdc_fini = string.replace(jdc_formate,'\r\n','\n') - - if not save_in_file(fichierSortie,self.jdc_fini) : - self.affiche_infos("Problème à la sauvegarde du fichier") - return 0 - else : - self.affiche_infos("sauvegarde effectuée") - return 1 - - - def affiche_infos(self,mess): - print mess - diff --git a/InterfaceTK/compobase.py b/InterfaceTK/compobase.py deleted file mode 100644 index a287b7d2..00000000 --- a/InterfaceTK/compobase.py +++ /dev/null @@ -1,3 +0,0 @@ -from Editeur import Objecttreeitem -treeitem = Objecttreeitem.ObjectTreeItem -objet = None diff --git a/InterfaceTK/compobloc.py b/InterfaceTK/compobloc.py deleted file mode 100644 index e92d5199..00000000 --- a/InterfaceTK/compobloc.py +++ /dev/null @@ -1,42 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -from Tkinter import * -import Pmw - -from Editeur import Objecttreeitem -import compofact - - -class BLOCTreeItem(compofact.FACTTreeItem): - panel = compofact.FACTPanel - - def get_objet(self,name) : - for v in self.object.mc_liste: - if v.nom == name : return v - return None - - def iscopiable(self): - return 0 - - -import Accas -treeitem = BLOCTreeItem -objet = Accas.MCBLOC diff --git a/InterfaceTK/compocomm.py b/InterfaceTK/compocomm.py deleted file mode 100644 index 949014c6..00000000 --- a/InterfaceTK/compocomm.py +++ /dev/null @@ -1,170 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -from Tkinter import * -import Pmw -import string - -from Editeur import Objecttreeitem -import panels -import fontes - -Fonte_Commentaire = fontes.standard_italique - -class COMMPanel(panels.OngletPanel): - - def init(self): - """ - Initialise les frame des panneaux contextuels relatifs à un COMMENTAIRE - """ - nb = Pmw.NoteBook(self,raisecommand=self.raisecmd) - nb.pack(fill = 'both', expand = 1) - self.nb=nb - nb.add('TexteComm', tab_text='Texte Commentaire') - nb.add('Commande', tab_text='Nouvelle Commande') - nb.add('Commentaire',tab_text='Paramètre/Commentaire') - self.makeCOMMPage(nb.page("TexteComm")) - self.makeCommandePage(nb.page("Commande")) - self.makeParamCommentPage_for_etape(nb.page("Commentaire")) - nb.tab('TexteComm').focus_set() - self.enlevebind() - self.creebind() - nb.setnaturalsize() - - def makeCOMMPage(self,page): - """ - Crée la page qui permet d'afficher et d'éditer le texte du commentaire - """ - self.frame_valeur = Frame(page) - self.frame_valeur.place(relwidth=0.9,relheight=0.9,relx=0.05,rely=0.05,anchor='nw') - self.widget_text = Pmw.ScrolledText(self.frame_valeur, - borderframe=1, - labelpos='n', - label_text = 'Texte du commentaire\n ') - self.widget_text.pack(side='top',expand=1,fill='both') - self.widget_text.configure(hscrollmode='dynamic', - vscrollmode='dynamic') - self.widget_text.component('text').configure(background = 'white') - self.make_buttons() - self.display_valeur() - - def make_buttons(self): - """ - Crée les boutons du panneau - """ - #self.bouton_sup.place_forget() - #self.bouton_doc.place_forget() - #self.bouton_val = Button(self.fr_but,text='Valider',command=self.change_valeur,width=14) - #self.bouton_ann = Button(self.fr_but,text='Annuler',command=self.display_valeur,width=14) - - #self.bouton_val.place(relx=0.25,rely=0.5,relheight=0.8,anchor='center') - #self.bouton_ann.place(relx=0.50,rely=0.5,relheight=0.8,anchor='center') - #self.bouton_sup.place(relx=0.75,rely=0.5,relheight=0.8,anchor='center') - - self.bouton_sup.pack_forget() - self.bouton_doc.pack_forget() - self.bouton_val = Button(self.fr_but,text='Valider',command=self.change_valeur) - self.bouton_ann = Button(self.fr_but,text='Annuler',command=self.display_valeur) - - self.bouton_val.pack(side='left',padx=5, pady=5) - self.bouton_ann.pack(side='left',padx=5, pady=5) - self.bouton_sup.pack(side='right',padx=5, pady=5) - - def change_valeur(self): - """ - Stocke la nouvelle valeur donnée par l'utilisateur comme valeur du commentaire - """ - if self.parent.modified == 'n' : self.parent.init_modif() - new_valeur = self.widget_text.get() - self.node.item.set_valeur(new_valeur) - self.node.update() - - def display_valeur(self): - """ - Affiche dans self.widget_text la valeur de l'objet commentaire - (annule d'éventuelles modifications faite par l'utilisateur) - """ - t=self.node.item.get_valeur() - try: - self.widget_text.settext(unicode(t)) - except: - # Si probleme avec unicode - self.widget_text.settext(t) - -class COMMTreeItem(Objecttreeitem.ObjectTreeItem): - panel = COMMPanel - - def init(self): - self.setfunction = self.set_valeur - - def GetIconName(self): - """ - Retourne le nom de l'icône associée au noeud qui porte self, - dépendant de la validité de l'objet - NB : un commentaire est toujours valide ... - """ - return "ast-white-percent" - - def GetLabelText(self): - """ Retourne 3 valeurs : - - le texte à afficher dans le noeud représentant l'item - - la fonte dans laquelle afficher ce texte - - la couleur du texte - """ - return 'commentaire',Fonte_Commentaire,None - - def get_valeur(self): - """ - Retourne la valeur de l'objet Commentaire cad son texte - """ - return self.object.get_valeur() or '' - - def GetText(self): - texte = self.object.valeur - texte = string.split(texte,'\n')[0] - if len(texte) < 25 : - return texte - else : - return texte[0:24] - - def set_valeur(self,valeur): - """ - Afefcte valeur à l'objet COMMENTAIRE - """ - self.object.set_valeur(valeur) - - def GetSubList(self): - """ - Retourne la liste des fils de self - """ - return [] - - - def get_objet_commentarise(self): - """ - La méthode get_objet_commentarise() de la classe compocomm.COMMTreeItem - surcharge la méthode get_objet_commentarise de la classe Objecttreeitem.ObjectTreeItem - elle a pour but d'empecher l'utilisateur final de commentariser un commentaire. - """ - raise Exception( 'Citoyen : tu peux "commentariser" une commande MAIS PAS UN COMMENTAIRE' ) - -import Extensions -treeitem =COMMTreeItem -objet = Extensions.commentaire.COMMENTAIRE diff --git a/InterfaceTK/compocommandecomm.py b/InterfaceTK/compocommandecomm.py deleted file mode 100644 index c7e55d78..00000000 --- a/InterfaceTK/compocommandecomm.py +++ /dev/null @@ -1,182 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -import traceback -from Tkinter import * -import Pmw -import string -from widgets import showerror - -from Editeur import Objecttreeitem -import panels -import fontes - -Fonte_Commentaire = fontes.standard_italique - -class COMMANDE_COMMPanel(panels.OngletPanel): - """ - Classe servant à définir le panel associé à une commande commentarisée - """ - def init(self): - """ - Initialise les frame des panneaux contextuels relatifs à une commande commentarisée - """ - panneau=Frame(self) - panneau.pack(expand=1,fill='both') - self.make_buttons() - self.makeCOMMPage(panneau) - self.enlevebind() - - def makeCOMMPage(self,page): - """ - Crée la page qui permet d'afficher et d'éditer le texte de la commande commentarisée - """ - self.frame_valeur = Frame(page) - self.frame_valeur.place(relwidth=0.9,relheight=0.9,relx=0.05,rely=0.05,anchor='nw') - self.widget_text = Pmw.ScrolledText(self.frame_valeur, - borderframe=1, - labelpos='n', - label_text = 'Texte de la commande\n ') - self.widget_text.pack(side='top',expand=1,fill='both') - self.widget_text.configure(hscrollmode='dynamic', - vscrollmode='dynamic') - self.display_valeur() - - def make_buttons(self): - """ - Crée les boutons du panneau - """ - #self.bouton_sup.place_forget() - #self.bouton_doc.place_forget() - #self.bouton_val = Button(self.fr_but,text='Valider',command=self.change_valeur,width=14) - #self.bouton_ann = Button(self.fr_but,text='Annuler',command=self.display_valeur,width=14) - #self.bouton_unc = Button(self.fr_but,text='Décommentariser',command=self.uncomment,width=14) - - #self.bouton_val.place(relx=0.1,rely=0.5,relheight=1,relwidth=0.20,anchor='center') - #self.bouton_ann.place(relx=0.30,rely=0.5,relheight=1,relwidth=0.20,anchor='center') - #self.bouton_sup.place(relx=0.50,rely=0.5,relheight=1,relwidth=0.20,anchor='center') - #self.bouton_unc.place(relx=0.75,rely=0.5,relheight=1,relwidth=0.25,anchor='center') - - self.bouton_sup.pack_forget() - self.bouton_doc.pack_forget() - self.bouton_val = Button(self.fr_but,text='Valider',command=self.change_valeur) - self.bouton_ann = Button(self.fr_but,text='Annuler',command=self.display_valeur) - self.bouton_unc = Button(self.fr_but,text='Décommentariser',command=self.uncomment) - self.bouton_val.pack(side='left',padx=5, pady=5) - self.bouton_ann.pack(side='left',padx=5, pady=5) - self.bouton_sup.pack(side='left',padx=5, pady=5) - self.bouton_unc.pack(side='right',padx=5, pady=5) - - def change_valeur(self): - """ - Stocke la nouvelle valeur donnée par l'utilisateur comme valeur de la commande commentarisée - """ - if self.parent.modified == 'n' : self.parent.init_modif() - new_valeur = self.widget_text.get() - self.node.item.set_valeur(new_valeur) - self.node.update() - - def display_valeur(self): - """ - Affiche dans self.widget_text la valeur de la commande commentarisée - (annule d'éventuelles modifications faite par l'utilisateur) - """ - self.widget_text.settext(self.node.item.get_valeur()) - - def uncomment(self): - """ - Réalise la décommentarisation de self - """ - try: - pos=self.node.parent.children.index(self.node) - commande,nom = self.node.item.uncomment() - self.node.parent.children[pos].select() - except Exception,e: - showerror("Erreur !",str(e)) - return - #self.parent.appli.bureau.JDCDisplay_courant.ReplaceObjectNode(self.node,commande,nom) - -class COMMANDE_COMMTreeItem(Objecttreeitem.ObjectTreeItem): - panel = COMMANDE_COMMPanel - - def init(self): - self.setfunction = self.set_valeur - - def GetIconName(self): - """ - Retourne le nom de l'icône associée au noeud qui porte self, - dépendant de la validité de l'objet - NB : une commande commentarisée est toujours valide ... - """ - if self.isvalid(): - return "ast-green-percent" - else: - return "ast-red-percent" - - def GetLabelText(self): - """ Retourne 3 valeurs : - - le texte à afficher dans le noeud représentant l'item - - la fonte dans laquelle afficher ce texte - - la couleur du texte - """ - return 'commande commentarisée',Fonte_Commentaire,None - - def get_valeur(self): - """ - Retourne la valeur de la commande commentarisée cad son texte - """ - return self.object.get_valeur() or '' - - def GetText(self): - texte = self.object.valeur - texte = string.split(texte,'\n')[0] - if len(texte) < 25 : - return texte - else : - return texte[0:24] - - def set_valeur(self,valeur): - """ - Afefcte valeur à l'objet commande commentarisée - """ - self.object.set_valeur(valeur) - - def GetSubList(self): - """ - Retourne la liste des fils de self - """ - return [] - - def uncomment(self): - """ - Demande à l'objet commande commentarisée de se décommentariser. - Si l'opération s'effectue correctement, retourne l'objet commande - et éventuellement le nom de la sd produite, sinon lève une exception - """ - try: - commande,nom = self.object.uncomment() - except Exception,e: - traceback.print_exc() - raise e - return commande,nom - -import Accas -treeitem =COMMANDE_COMMTreeItem -objet = Accas.COMMANDE_COMM diff --git a/InterfaceTK/compoerror.py b/InterfaceTK/compoerror.py deleted file mode 100644 index 74e0c46c..00000000 --- a/InterfaceTK/compoerror.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -# Modules Python -from Tkinter import Label,Button - -#Modules Eficas -from Noyau.N_OBJECT import ErrorObj -from Editeur import Objecttreeitem -import panels - -class ERRORPanel(panels.Panel_Inactif): - def creer_texte(self): - texte = """Le noeud sélectionné correspond à un objet erroné """ - label = Label(self,text=texte,justify='center') - label.place(relx=0.5,rely=0.4,relwidth=0.8,anchor='center') - bouton = Button(self,text = "Supprimer", command=self.supprimer) - bouton.place(relx=0.5,rely=0.5,anchor='center') - -class ERRORTreeItem(Objecttreeitem.AtomicObjectTreeItem): - panel = ERRORPanel - def GetIconName(self): - return "ast-red-ball" - - -treeitem =ERRORTreeItem -objet = ErrorObj - diff --git a/InterfaceTK/compofact.py b/InterfaceTK/compofact.py deleted file mode 100644 index 0d984381..00000000 --- a/InterfaceTK/compofact.py +++ /dev/null @@ -1,150 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -import Pmw -from Editeur import Objecttreeitem -import panels - -class FACTPanel(panels.OngletPanel) : - def init(self) : - nb = Pmw.NoteBook(self,raisecommand=self.raisecmd) - nb.pack(fill = 'both', expand = 1) - self.nb=nb - nb.add('Mocles', tab_text='Ajouter mots-clés') - panneau=Pmw.PanedWidget(nb.page("Mocles"), - orient='horizontal') - panneau.add('left',min=0.4,max=0.6,size=0.5) - panneau.add('right',min=0.4,max=0.6,size=0.5) - panneau.pack(expand=1,fill='both') - self.makeMoclesPage(panneau.pane('left')) - self.makeReglesPage(panneau.pane('right')) - nb.tab('Mocles').focus_set() - nb.setnaturalsize() - self.enlevebind() - self.creebind() - self.affiche() - -import treewidget -class Node(treewidget.Node): - def doPaste(self,node_selected): - objet_a_copier = self.item.get_copie_objet() - child=node_selected.doPaste_MCF(objet_a_copier) - return child - - def doPaste_MCF(self,objet_a_copier): - child = self.parent.append_child(objet_a_copier, - pos=self.item, - retour='oui') - return child - - -class FACTTreeItem(Objecttreeitem.ObjectTreeItem): - panel = FACTPanel - itemNode=Node - - def IsExpandable(self): - return 1 - - def GetText(self): - return '' - - def GetLabelText(self): - """ Retourne 3 valeurs : - - le texte à afficher dans le noeud représentant l'item - - la fonte dans laquelle afficher ce texte - - la couleur du texte - """ - # None --> fonte et couleur par défaut - return self.object.getlabeltext(),None,None - - def isvalid(self): - return self.object.isvalid() - - def iscopiable(self): - return 1 - - def GetIconName(self): - if self.object.isvalid(): - return "ast-green-los" - elif self.object.isoblig(): - return "ast-red-los" - else: - return "ast-yel-los" - - def keys(self): - keys=self.object.mc_dict.keys() - return keys - - def GetSubList(self): - """ - Reactualise la liste des items fils stockes dans self.sublist - """ - liste=self.object.mc_liste - sublist=[None]*len(liste) - # suppression des items lies aux objets disparus - for item in self.sublist: - old_obj=item.getObject() - if old_obj in liste: - pos=liste.index(old_obj) - sublist[pos]=item - else: - pass # objets supprimes ignores - # ajout des items lies aux nouveaux objets - pos=0 - for obj in liste: - if sublist[pos] is None: - # nouvel objet : on cree un nouvel item - def setfunction(value, object=obj): - object.setval(value) - item = self.make_objecttreeitem(self.appli, obj.nom + " : ", obj, setfunction) - sublist[pos]=item - pos=pos+1 - - self.sublist=sublist - return self.sublist - - def additem(self,name,pos): - #print "compofact.additem",name,pos - objet = self.object.addentite(name,pos) - return objet - - def suppitem(self,item) : - """ - Cette methode a pour fonction de supprimer l'item passé en argument - des fils de l'item FACT qui est son pere - - item = item du MOCLE à supprimer du MOCLE père - - item.getObject() = MCSIMP ou MCBLOC - """ - itemobject=item.getObject() - if itemobject.isoblig() : - self.appli.affiche_infos('Impossible de supprimer un mot-clé obligatoire ') - return 0 - - if self.object.suppentite(itemobject): - message = "Mot-clé " + itemobject.nom + " supprimé" - self.appli.affiche_infos(message) - return 1 - else: - self.appli.affiche_infos('Pb interne : impossible de supprimer ce mot-clé') - return 0 - -import Accas -objet = Accas.MCFACT -treeitem = FACTTreeItem diff --git a/InterfaceTK/compoformule.py b/InterfaceTK/compoformule.py deleted file mode 100644 index e6f22793..00000000 --- a/InterfaceTK/compoformule.py +++ /dev/null @@ -1,410 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -""" -Ce module contient les classes permettant de définir les objets graphiques -représentant un objet de type FORMULE, cad le panneau et l'item de l'arbre -d'EFICAS -""" - -# import modules Python -from Tkinter import * -import Pmw -import string - -# import modules EFICAS -import widgets -import panels -import fontes -import compooper - -Fonte_TITRE = fontes.standard_gras_souligne - - -class FORMULEPanel(panels.OngletPanel): - """ - Classe servant à construire le panneau associé à un paramètre. - C'est au moyen de ce panneau que l'utilisateur peut accéder - aux nom et valeur du paramètre en vue éventuellement de les - modifier. - """ - - def init(self): - nb = Pmw.NoteBook(self,raisecommand=self.raisecmd) - nb.pack(fill = 'both', expand = 1) - self.nb=nb - nb.add('Formule', tab_text='Définition Formule') - nb.add('Commande', tab_text='Nouvelle Commande') - nb.add('Commentaire',tab_text='Paramètre/Commentaire') - self.makeFormulePage(nb.page("Formule")) - self.makeCommandePage(nb.page("Commande")) - self.makeParamCommentPage_for_etape(nb.page("Commentaire")) - nb.tab('Formule').focus_set() - self.enlevebind() - self.creebind() - nb.setnaturalsize() - - def makeFormulePage(self,page): - """ - Crée la page qui permet d'afficher et d'éditer le texte de la FORMULE - """ - self.frame_valeur = Frame(page) - self.frame_valeur.pack(fill='both',expand=1) - #self.frame_valeur.place(relwidth=0.95,relheight=0.95,relx=0.05,rely=0.05,anchor='nw') - #self.frame_valeur.place(relwidth=0.9,relheight=0.9,relx=0.05,rely=0.05,anchor='nw') - # affichage du titre du panneau - self.titre = StringVar() - self.titre.set("FORMULE "+self.node.item.get_nom()) - - self.entry_nom = Entry(self.frame_valeur) - #Label(self.frame_valeur,textvariable=self.titre,font=Fonte_TITRE).place(relx=0.5,rely=0.,anchor='n') - Label(self.frame_valeur,textvariable=self.titre,font=Fonte_TITRE).grid(row=0,columnspan=2,padx=5,pady=5) - # création des labels et entries associés aux nom, type retourné, arguments et corps de la FORMULE - - #Label(self.frame_valeur,text= 'Nom de la formule : ').place(relx=0.,rely=0.1) - Label(self.frame_valeur,text= 'Nom de la formule : ').grid(row=1,sticky=W,padx=5,pady=5) - #Label(self.frame_valeur,text= 'Arguments : ').place(relx=0.,rely=0.40) - Label(self.frame_valeur,text= 'Arguments : ').grid(row=2,sticky=W,padx=5,pady=5) - self.entry_arg = Entry(self.frame_valeur) - #Label(self.frame_valeur,text= 'Expression : ').place(relx=0.,rely=0.65) - Label(self.frame_valeur,text= 'Expression : ').grid(row=4,sticky=W,padx=5,pady=5) - self.entry_exp = Entry(self.frame_valeur) - - # binding sur les entries - self.entry_nom.bind("",self.verif_nom) - self.entry_nom.bind("",self.verif_nom) - self.entry_arg.bind("",self.verif_arguments) - self.entry_arg.bind("",self.verif_arguments) - self.entry_exp.bind("",self.verif_corps) - self.entry_exp.bind("",self.verif_corps) - # affichage des entries - #self.entry_nom.place(relx=0.35,rely=0.10,relwidth=0.2) - self.entry_nom.grid(row=1,column=1,sticky=W,padx=5,pady=5) - #self.entry_arg.place(relx=0.35,rely=0.40,relwidth=0.4) - self.entry_arg.grid(row=2,column=1,sticky=W,padx=5,pady=5) - - # affichage d'une phrase d'aide pour les arguments - aide = """Entrer les arguments sous la forme -de VARIABLES séparées par des virgules (,) -Exemple X,Y,Z """ - #Label(self.frame_valeur,text=aide, justify="l").place(relx=0.5,rely=0.47,anchor='n') - Label(self.frame_valeur,text=aide, justify="l").grid(row=3,columnspan=2,padx=5,pady=5) - - #self.entry_exp.place(relx=0.35,rely=0.65,relwidth=0.60) - self.entry_exp.grid(row=4,column=1,sticky=W,padx=5,pady=5) - # affichage d'une phrase d'aide pour l'expression - aide = """Un retour de chariot dans une zone de saisie vous permet de vérifier si -la valeur que vous avez entrée est valide. -Ce n'est qu'après avoir appuyé sur le bouton Valider que les nouvelles -valeurs seront effectivement prises en compte.""" - #Label(self.frame_valeur,text=aide).place(relx=0.5,rely=0.75,anchor='n') - Label(self.frame_valeur,text=aide).grid(row=5,columnspan=2,padx=5,pady=5) - self.frame_valeur.columnconfigure(1,weight=1) - - # affichage des nom, type retourné, arguments et corps de la FORMULE - self.display_valeur() - # affichage des boutons - self.make_buttons() - # entry_nom prend le focus - self.entry_nom.focus() - - def make_buttons(self): - """ - Crée les boutons du panneau - """ - #self.bouton_sup.place_forget() - #self.bouton_doc.place_forget() - #self.bouton_val = Button(self.fr_but,text='Valider',command=self.change_valeur,width=14) - #self.bouton_ann = Button(self.fr_but,text='Annuler',command=self.display_valeur,width=14) - - #self.bouton_val.place(relx=0.15,rely=0.5,relheight=0.8,anchor='center') - #self.bouton_ann.place(relx=0.40,rely=0.5,relheight=0.8,anchor='center') - #self.bouton_sup.place(relx=0.65,rely=0.5,relheight=0.8,anchor='center') - #self.bouton_doc.place(relx=0.90,rely=0.5,relheight=0.8,anchor='center') - - self.bouton_sup.pack_forget() - self.bouton_doc.pack_forget() - self.bouton_val = Button(self.fr_but,text='Valider',command=self.change_valeur) - self.bouton_ann = Button(self.fr_but,text='Annuler',command=self.display_valeur) - - self.bouton_val.pack(side='left',padx=5, pady=5) - self.bouton_ann.pack(side='left',padx=5, pady=5) - self.bouton_sup.pack(side='left',padx=5, pady=5) - self.bouton_doc.pack(side='right',padx=5, pady=5) - - def change_valeur(self): - """ - Stocke la nouvelle FORMULE décrite par l'utilisateur - """ - if self.parent.modified == 'n' : self.parent.init_modif() - # on récupère les nouveaux nom, type retourné, arguments et corps de la FORMULE - new_nom = self.entry_nom.get() - new_typ="REEL" - new_arg = self.entry_arg.get() - new_exp = self.entry_exp.get() - self.verif_arguments() - self.verif_corps() - # on essaie de les stocker - test,erreur = self.node.item.save_formule(new_nom,new_typ,new_arg,new_exp) - if test : - # on a pu stocker les nouveaux paramètres : il faut rafraîchir l'affichage - self.node.update() - self.display_valeur() - self.parent.appli.affiche_infos("FORMULE %s modifiée" %self.node.item.get_nom()) - else: - # la formule est incorrecte : on affiche les erreurs - widgets.showerror("Formule incorrecte",erreur) - self.parent.appli.affiche_infos("FORMULE %s non modifiée" %self.node.item.get_nom()) - - def display_valeur(self): - """ - Affiche dans self.widget_text de la valeur de l'objet FORMULE - (annule d'éventuelles modifications faite par l'utilisateur) - """ - # on efface tout texte affiché dans les entries - self.entry_nom.delete(0,END) - self.entry_arg.delete(0,END) - self.entry_exp.delete(0,END) - # on rafraîchit le titre du panneau - self.titre.set('FORMULE '+self.node.item.get_nom()) - # on insére les nouveaux nom, type retourné, arguments et corps de la FORMULE - nom = self.node.item.get_nom() - if nom != '': - self.entry_nom.insert(END,nom) - args = self.node.item.get_args() - if args: - texte_args="" - for i in args : - if texte_args != "" : - texte_args = texte_args +"," - texte_args=texte_args + i - self.entry_arg.insert(END,texte_args) - corps = self.node.item.get_corps() - if corps : - self.entry_exp.insert(END,self.node.item.get_corps()) - - def verif_nom(self,event=None): - """ - Lance la vérification du nom présent dans entry_nom - """ - nom = self.entry_nom.get() - if nom == '': - test,erreur = 0,"Aucun nom fourni !" - else: - test,erreur = self.node.item.verif_nom(nom) - if not test: - widgets.showerror("Nom invalide",erreur) - self.entry_nom.focus() - self.entry_nom.selection_range(0,END) - self.parent.appli.affiche_infos("%s n'est pas un nom valide pour une FORMULE" %nom) - else: - self.parent.appli.affiche_infos("%s est un nom valide pour une FORMULE" %nom) - self.entry_arg.focus() - - def verif_arguments(self,event=None): - """ - Lance la vérification des arguments présents dans entry_arg - """ - arguments = self.entry_arg.get() - if arguments == '' : - test,erreur = 0,"Aucun argument fourni" - else: - test,erreur = self.node.item.verif_arguments(arguments) - if not test: - widgets.showerror("Argument(s) invalide(s)",erreur) - self.entry_arg.focus() - self.entry_arg.selection_range(0,END) - self.parent.appli.affiche_infos("Argument(s) invalide(s) pour une FORMULE") - else: - self.parent.appli.affiche_infos("Argument(s) valide(s) pour une FORMULE") - self.entry_exp.focus() - - def verif_corps(self,event=None): - """ - Lance la vérification du corps de formule présent dans entry_exp - """ - new_nom = self.entry_nom.get() - new_typ="REEL" - new_arg = self.entry_arg.get() - new_exp = self.entry_exp.get() - if new_exp == '': - test,erreur = 0,"Aucune expression fournie !" - else: - test,erreur = self.node.item.verif_formule_python((new_nom,new_typ,new_arg,new_exp)) - - if not test: - widgets.showerror("Corps de FORMULE invalide",erreur) - self.entry_exp.focus() - self.entry_exp.selection_range(0,END) - self.parent.appli.affiche_infos("Corps de FORMULE invalide") - else: - self.parent.appli.affiche_infos("Corps de FORMULE valide") - -class FORMULETreeItem(compooper.EtapeTreeItem): - """ - Classe servant à définir l'item porté par le noeud de l'arbre d'EFICAS - qui représente la FORMULE - """ - panel = FORMULEPanel - - def init(self): - self.setfunction = self.set_valeur - -# --------------------------------------------------------------------------- -# API de FORMULE pour l'arbre -# --------------------------------------------------------------------------- - def GetSubList(self): - """ - Retourne la liste des fils de self - On considère que FORMULE n'a pas de fils - --> modification par rapport à MACRO classique - """ - # dans EFICAS on ne souhaite pas afficher les mots-clés fils de FORMULE - # de façon traditionnelle - return [] - - def GetIconName(self): - """ - Retourne le nom de l'icône à afficher dans l'arbre - Ce nom dépend de la validité de l'objet - """ - if self.object.isactif(): - if self.object.isvalid(): - return "ast-green-square" - else: - return "ast-red-square" - else: - return "ast-white-text" - - def GetLabelText(self): - """ Retourne 3 valeurs : - - le texte à afficher dans le noeud représentant l'item - - la fonte dans laquelle afficher ce texte - - la couleur du texte - """ - if self.object.isactif(): - # None --> fonte et couleur par défaut - return self.labeltext,None,None - else: - return self.labeltext,fontes.standard_italique,None - -# --------------------------------------------------------------------------- -# Méthodes permettant la modification et la lecture des attributs -# du paramètre = API graphique de la FORMULE pour Panel et EFICAS -# --------------------------------------------------------------------------- - - def get_nom(self): - """ - Retourne le nom de la FORMULE - """ - return self.object.get_nom() - - def get_type(self): - """ - Retourne le type de la valeur retournée par la FORMULE - """ - return self.object.type_retourne - - def get_args(self): - """ - Retourne les arguments de la FORMULE - """ - args="" - for mot in self.object.mc_liste: - if mot.nom == 'NOM_PARA': - args=mot.valeur - break - if args : - if args[0] == "(" and args[-1] ==")": - args=args[1:-1] - # transforme en tuple si ce n est pas déjà le casa - try : - args=string.split(args,',') - except : - pass - return args - - def get_corps(self): - """ - Retourne le corps de la FORMULE - """ - corps="" - for mot in self.object.mc_liste: - if mot.nom == 'VALE': - corps=mot.valeur - break - return corps - - - def get_liste_types_autorises(self): - """ - Retourne la liste des types autorises pour les valeurs de sortie - d'une FORMULE - """ - return self.object.l_types_autorises - - def save_formule(self,new_nom,new_typ,new_arg,new_exp): - """ - Vérifie si (new_nom,new_typ,new_arg,new_exp) définit bien une FORMULE - licite : - - si oui, stocke ces paramètres comme nouveaux paramètres de la - FORMULE courante et retourne 1 - - si non, laisse les paramètres anciens de la FORMULE inchangés et - retourne 0 - """ - test,erreur = self.object.verif_formule_python(formule=(new_nom,new_typ,new_arg, - new_exp)) - if test : - # la formule est bien correcte : on sauve les nouveaux paramètres - test=self.object.update_formule_python(formule=(new_nom,new_typ,new_exp,new_arg)) - return test,erreur - -# --------------------------------------------------------------------------- -# Accès aux méthodes de vérification de l'objet FORM_ETAPE -# --------------------------------------------------------------------------- - - def verif_nom(self,nom): - """ - Lance la vérification du nom passé en argument - """ - return self.object.verif_nom(nom) - - def verif_arguments(self,arguments): - """ - Lance la vérification des arguments passés en argument - """ - return self.object.verif_arguments('('+arguments+')') - - def verif_formule(self,formule): - """ - Lance la vérification de FORMULE passée en argument - """ - return self.object.verif_formule(formule=formule) - - - def verif_formule_python(self,formule): - """ - Lance la vérification de FORMULE passée en argument - """ - return self.object.verif_formule_python(formule=formule) - -import Accas -treeitem =FORMULETreeItem -objet = Accas.FORM_ETAPE diff --git a/InterfaceTK/compojdc.py b/InterfaceTK/compojdc.py deleted file mode 100644 index fb9b7d76..00000000 --- a/InterfaceTK/compojdc.py +++ /dev/null @@ -1,168 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -import Pmw -from Editeur import Objecttreeitem -import panels - -from widgets import ListeChoix - -class JDCPanel(panels.OngletPanel): - def init(self): - """ Initialise les frame des panneaux contextuels relatifs à un JDC """ - panneau=Pmw.PanedWidget(self,orient='horizontal') - panneau.add('left',min=0.4,max=0.6,size=0.5) - panneau.add('right',min=0.4,max=0.6,size=0.5) - panneau.pack(expand=1,fill='both') - self.bouton_com.pack_forget() - self.makeJDCPage(panneau.pane('left')) - self.makeReglesPage(panneau.pane('right')) - self.enlevebind() - - def makeReglesPage(self,page) : - regles = [] - regles = self.node.item.get_regles() - texte_regles = [] - l_regles_en_defaut=[] - if len(regles) > 0: - l_noms_etapes = self.node.item.get_l_noms_etapes() - i = 0 - for regle in regles : - texte_regles.append(regle.gettext()) - texte,test = regle.verif(l_noms_etapes) - if test == 0 : l_regles_en_defaut.append(i) - i = i+1 - Liste = ListeChoix(self,page,texte_regles,liste_marques=l_regles_en_defaut,active='non',titre="Règles") - Liste.affiche_liste() - # aide associée au panneau - bulle_aide="""Ce panneau contient la liste des règles qui s'appliquent à l'objet - en cours d'édition. - - en noir : règles valides - - en rouge : règles violées""" - Liste.MCbox.bind("", lambda e,s=self,a=bulle_aide : s.parent.appli.affiche_aide(e,a)) - Liste.MCbox.bind("",self.parent.appli.efface_aide) - -import treewidget -class Node(treewidget.Node): - def doPaste_Commande(self,objet_a_copier): - """ - Réalise la copie de l'objet passé en argument qui est nécessairement - une commande - """ - #child = self.item.append_child(objet_a_copier,pos='first') - child = self.append_child(objet_a_copier,pos='first',retour='oui') - #if child is None : return 0 - return child - - -class JDCTreeItem(Objecttreeitem.ObjectTreeItem): - panel = JDCPanel - itemNode=Node - - def IsExpandable(self): - return 1 - - def GetText(self): - return " " - - def GetLabelText(self): - # None --> fonte et couleur par défaut - return self.object.nom,None,None - - def get_jdc(self): - """ - Retourne l'objet pointé par self - """ - return self.object - - def GetIconName(self): - if self.object.isvalid(): - return "ast-green-square" - else: - return "ast-red-square" - - def keys(self): - if self.object.etapes_niveaux != []: - return range(len(self.object.etapes_niveaux)) - else: - return range(len(self.object.etapes)) - - def additem(self,name,pos): - cmd = self._object.addentite(name,pos) - return cmd - - def suppitem(self,item) : - # item = item de l'ETAPE à supprimer du JDC - # item.getObject() = ETAPE ou COMMENTAIRE - # self.object = JDC - itemobject=item.getObject() - if self.object.suppentite(itemobject): - if itemobject.nature == "COMMENTAIRE" : - message = "Commentaire supprimé" - else : - message = "Commande " + itemobject.nom + " supprimée" - self.appli.affiche_infos(message) - return 1 - else: - self.appli.affiche_infos("Pb interne : impossible de supprimer cet objet") - return 0 - - def GetSubList(self): - """ - Retourne la liste des items fils de l'item jdc. - Cette liste est conservee et mise a jour a chaque appel - """ - if self.object.etapes_niveaux != []: - liste = self.object.etapes_niveaux - else: - liste = self.object.etapes - sublist=[None]*len(liste) - # suppression des items lies aux objets disparus - for item in self.sublist: - old_obj=item.getObject() - if old_obj in liste: - pos=liste.index(old_obj) - sublist[pos]=item - else: - pass # objets supprimes ignores - # ajout des items lies aux nouveaux objets - pos=0 - for obj in liste: - if sublist[pos] is None: - # nouvel objet : on cree un nouvel item - item = self.make_objecttreeitem(self.appli, obj.nom + " : ", obj) - sublist[pos]=item - pos=pos+1 - - self.sublist=sublist - return self.sublist - - def get_l_noms_etapes(self): - """ Retourne la liste des noms des étapes de self.object""" - return self.object.get_l_noms_etapes() - - def get_liste_cmd(self): - #print "get_liste_cmd",self.object.niveau.definition - listeCmd = self.object.niveau.definition.get_liste_cmd() - return listeCmd - -import Accas -treeitem =JDCTreeItem -objet = Accas.JDC diff --git a/InterfaceTK/compomacro.py b/InterfaceTK/compomacro.py deleted file mode 100644 index cc927fa2..00000000 --- a/InterfaceTK/compomacro.py +++ /dev/null @@ -1,311 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -# Modules Python -import os,sys,string -import types -import Tkinter -import Pmw -import traceback - -# Modules Eficas -from Editeur import Objecttreeitem -import panels -import fontes -import compooper -import convert -from widgets import askopenfilename -from widgets import Fenetre,FenetreYesNo -from widgets import showinfo,showerror - -# -__version__="$Name: BR_dev_V1_13 $" -__Id__="$Id: compomacro.py,v 1.1.4.3 2007-10-29 12:42:18 pnoyret Exp $" -# - -class MACROPanel(panels.OngletPanel): - def init(self): - nb = Pmw.NoteBook(self,raisecommand=self.raisecmd) - nb.pack(fill = 'both', expand = 1) - self.nb=nb - nb.add('Mocles', tab_text='Ajouter mots-clés') - typsd=self.node.item.object.get_type_produit() - ficini = self.node.item.wait_fichier_init() - if typsd != None: - nb.add('Concept', tab_text='Nommer concept') - if ficini == 1: - nb.add('Fichierinit',tab_text = 'Fichier %s' %self.node.item.get_nom()) - nb.add('Commande', tab_text='Nouvelle Commande') - nb.add('Commentaire',tab_text='Paramètre/Commentaire') - panneau=Pmw.PanedWidget(nb.page("Mocles"), - orient='horizontal') - panneau.add('left',min=0.4,max=0.6,size=0.5) - panneau.add('right',min=0.4,max=0.6,size=0.5) - panneau.pack(expand=1,fill='both') - self.makeCommandePage(nb.page("Commande")) - if typsd != None: - self.makeConceptPage(nb.page("Concept")) - if ficini == 1 : - self.makeFichierPage(nb.page('Fichierinit')) - self.makeMoclesPage(panneau.pane('left')) - self.makeReglesPage(panneau.pane('right')) - self.makeParamCommentPage_for_etape(nb.page("Commentaire")) - nb.tab('Mocles').focus_set() - nb.setnaturalsize() - self.enlevebind() - self.creebind() - self.affiche() - - def makeFichierPage(self,page): - """ - Affiche la page d'onglet correspondant au changement du fichier - dont a besoin la macro - """ - titre = Tkinter.Label(page,text="La commande %s requiert un fichier " %self.node.item.get_nom()) - titre.place(relx=0.5,rely=0.2,anchor='center') - frameMain=Tkinter.Frame(page) - frameMain.place(relx=0.5,rely=0.4,anchor='center',relwidth=1.) - Tkinter.Label(frameMain,text="Fichier :").pack(side='left',padx=5) - self.entry = Tkinter.Entry(frameMain,relief='sunken',bg='white') - self.entry.pack(side='left',padx=5,fill='x',expand=1) - frameButtons=Tkinter.Frame(page) - but1=Tkinter.Button(frameButtons,text='Valider',command = self.change_fichier_init) - but2=Tkinter.Button(frameButtons,text='Browse',command = self.browse_fichier_init) - but3=Tkinter.Button(frameButtons,text='Annuler',command = self.annule_fichier_init) - but1.grid(row=0,column=0,padx=5,pady=5) - but2.grid(row=0,column=1,padx=5,pady=5) - but3.grid(row=0,column=2,padx=5,pady=5) - frameButtons.place(relx=0.5,rely=0.6,anchor='center') - - if hasattr(self.node.item.object,'fichier_ini'): - if self.node.item.object.fichier_ini : - self.entry.insert(0,self.node.item.object.fichier_ini) - self.entry.focus() - - def convert_file(self,file): - """ - Methode pour convertir le fichier file dans le format courant - """ - format=self.parent.appli.format_fichier.get() - if convert.plugins.has_key(format): - # Le convertisseur existe on l'utilise - p=convert.plugins[format]() - p.readfile(file) - text=p.convert('execnoparseur') - if not p.cr.estvide(): - self.parent.appli.affiche_infos("Erreur à la conversion") - Fenetre(self, - titre="compte-rendu d'erreurs, EFICAS ne sait pas convertir ce fichier", - texte = str(p.cr)) - return None - return text - else: - # Il n'existe pas c'est une erreur - self.parent.appli.affiche_infos("Type de fichier non reconnu") - showerror("Type de fichier non reconnu","EFICAS ne sait pas ouvrir ce type de fichier") - return None - - def change_fichier_init(self,event=None): - """ - Effectue le changement de fichier d'initialisation s'il est valide - """ - new_fic = self.entry.get() - if not os.path.isfile(new_fic) : - showinfo("Fichier introuvable","Le fichier que vous avez saisi\n"+ - "n'est pas un nom de fichier valide !") - self.parent.appli.affiche_infos("Fichier introuvable") - return - # On convertit le fichier - text=self.convert_file(new_fic) - # Si probleme a la lecture-conversion on arrete le traitement - if not text: - return - - try: - self.node.item.object.change_fichier_init(new_fic,text) - self.parent.appli.affiche_infos("Fichier %s modifié" %self.node.item.get_nom()) - except: - # Erreurs lors de l'evaluation de text dans un JDC auxiliaire - self.parent.appli.affiche_infos("Fichier invalide") - l=traceback.format_exception_only("Fichier invalide",sys.exc_info()[1]) - f=FenetreYesNo(self.parent.appli,titre="Fichier invalide : voulez vous retablir l ancien fichier ?", - texte="Erreur dans l'interprétation du nouveau fichier ...\n\n"+string.join(l), - yes="Retablir",no="Changer") - f.wait() - reponse=f.result - if reponse: - # On retablit l'ancien fichier - self.entry.delete(0,Tkinter.END) - self.node.item.object.restore_fichier_init() - self.parent.appli.affiche_infos("Fichier invalide ... Ancien fichier restauré") - fic=self.node.item.object.fichier_ini - if fic: - self.entry.insert(0,fic) - else: - self.node.item.object.force_fichier_init() - self.parent.appli.affiche_infos("Fichier invalide ... Nouveau fichier mémorisé") - - def annule_fichier_init(self,event=None): - """ Restaure dans self.entry le nom de fichier_init""" - self.entry.delete(0,Tkinter.END) - if self.node.item.object.fichier_ini: - self.entry.insert(0,self.node.item.object.fichier_ini) - - def browse_fichier_init(self,event=None): - """ - Propose à l'utilisateur une Bsf et retourne le fichier - sélectionné dans self.entry - """ - file = askopenfilename(title="Choix du fichier %s" %self.node.item.get_nom()) - if file : - self.entry.delete(0,Tkinter.END) - self.entry.insert(0,file) - - def update_panel(self): - if hasattr(self,"entry"): - self.annule_fichier_init() - -class MACROTreeItem(compooper.EtapeTreeItem): - """ Cette classe hérite d'une grande partie des comportements - de la classe compooper.EtapeTreeItem - """ - panel=MACROPanel - -class INCLUDETreeItemBase(MACROTreeItem): - rmenu_specs=[("View","makeView"), - ("Edit","makeEdit"), - ] - - def __init__(self,appli, labeltext, object, setfunction): - MACROTreeItem.__init__(self,appli, labeltext, object, setfunction) - - def iscopiable(self): - """ - Retourne 1 si l'objet est copiable, 0 sinon - """ - return 0 - - def makeEdit(self,appli,node): - #print "makeEdit",self.object,self.object.nom - #print "makeEdit",self.object.jdc_aux,self.object.jdc_aux.nom - #print "makeEdit",self.object.jdc_aux.context_ini - if self.object.text_converted == 0: - # Le texte du fichier inclus n'a pas pu etre converti par le module convert - msg="Le fichier de commande n'a pas pu etre converti pour etre editable par Eficas\n\n" - msg=msg+self.object.text_error - Fenetre(self,titre="Include non editable",texte=msg,wrap='none') - return - - if not hasattr(self.object,"jdc_aux") or self.object.jdc_aux is None: - #L'include n'est pas initialise - self.object.build_include(None,"") - - # On cree un nouvel onglet dans le bureau - appli.bureau.ShowJDC(self.object.jdc_aux,self.object.jdc_aux.nom, - label_onglet=None, - JDCDISPLAY=macrodisplay.MACRODISPLAY) - - def makeView(self,appli,node): - if not hasattr(self.object,"jdc_aux") or self.object.jdc_aux is None: - showerror("Include vide", - "L'include doit etre correctement initialisé pour etre visualisé") - return - - nom=self.object.nom - if hasattr(self.object,'fichier_ini'): - if self.object.fichier_ini is None: - nom=nom+' '+"Fichier non défini" - else: - nom=nom+' '+self.object.fichier_ini - macdisp=macrodisplay.makeMacroDisplay(appli,self,nom) - -class INCLUDEPanel(MACROPanel): - def makeFichierPage(self,page): - """ - Affiche la page d'onglet correspondant au changement du fichier INCLUDE - """ - if not hasattr(self.node.item.object,'fichier_ini'): - titre = Tkinter.Label(page,text="L'INCLUDE n'a pas de fichier associé\nIl faut d'abord choisir un numero d'unité " ) - titre.place(relx=0.5,rely=0.5,anchor='center') - else: - MACROPanel.makeFichierPage(self,page) - -class INCLUDETreeItem(INCLUDETreeItemBase): - panel=INCLUDEPanel - -class POURSUITETreeItem(INCLUDETreeItemBase): - def makeEdit(self,appli,node): - if self.object.text_converted == 0: - # Le texte du fichier inclus n'a pas pu etre converti par le module convert - msg="Le fichier de commande n'a pas pu etre converti pour etre editable par Eficas\n\n" - msg=msg+self.object.text_error - Fenetre(self,titre="Poursuite non editable",texte=msg,wrap='none') - return - - if not hasattr(self.object,"jdc_aux") or self.object.jdc_aux is None: - #La poursuite n'est pas initialisee - text="""DEBUT() -FIN()""" - self.object.build_poursuite(None,text) - - # On cree un nouvel onglet dans le bureau - appli.bureau.ShowJDC(self.object.jdc_aux,self.object.jdc_aux.nom, - label_onglet=None, - JDCDISPLAY=macrodisplay.MACRODISPLAY) - - def makeView(self,appli,node): - if not hasattr(self.object,"jdc_aux") or self.object.jdc_aux is None: - showerror("Poursuite vide","Une POURSUITE doit etre correctement initialisée pour etre visualisée") - return - nom=self.object.nom - if hasattr(self.object,'fichier_ini'): - if self.object.fichier_ini is None: - nom=nom+' '+"Fichier non défini" - else: - nom=nom+' '+self.object.fichier_ini - macdisp=macrodisplay.makeMacroDisplay(appli,self,nom) - -class INCLUDE_MATERIAUTreeItem(INCLUDETreeItemBase): - rmenu_specs=[("View","makeView"), - ] - def iscopiable(self): - """ - Retourne 1 si l'objet est copiable, 0 sinon - """ - return 1 - - -def treeitem(appli, labeltext, object, setfunction=None): - """ Factory qui retourne l'item adapté au type de macro : - INCLUDE, POURSUITE, MACRO - """ - if object.nom == "INCLUDE_MATERIAU": - return INCLUDE_MATERIAUTreeItem(appli, labeltext, object, setfunction) - elif object.nom == "INCLUDE": - return INCLUDETreeItem(appli, labeltext, object, setfunction) - elif object.nom == "POURSUITE": - return POURSUITETreeItem(appli, labeltext, object, setfunction) - else: - return MACROTreeItem(appli, labeltext, object, setfunction) - -import Accas -objet=Accas.MACRO_ETAPE - -import macrodisplay diff --git a/InterfaceTK/compomclist.py b/InterfaceTK/compomclist.py deleted file mode 100644 index ba3704ca..00000000 --- a/InterfaceTK/compomclist.py +++ /dev/null @@ -1,225 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -import types -from Tkinter import * -import Pmw - -from Noyau.N_OBJECT import ErrorObj -from Editeur import Objecttreeitem -import panels -import traceback - -class MCLISTPanel(panels.Panel): - def init(self): - test_ajout = self.node.item.ajout_possible() - nom_mcfact = self.node.item.get_nom() - if test_ajout: - texte = "Pour ajouter une autre occurrence du mot-clé facteur %s, cliquez ci-dessous" %nom_mcfact - else: - texte = "Vous ne pouvez pas ajouter une autre occurrence du mot-clé facteur %s ?" %nom_mcfact - self.label = Label(self,text = texte) - self.label.place(relx=0.5,rely=0.4,anchor='center') - if test_ajout: - self.but=Button(self,text="AJOUTER",command=self.ajout_occurrence) - self.but.place(relx=0.5,rely=0.6,anchor='center') - #Button(self,text="NON",command=None).place(relx=0.6,rely=0.6,anchor='center') - - def ajout_occurrence(self,event=None): - self.node.parent.append_child(self.node.item.get_nom()) - -import compofact -import compoerror -import treewidget - -class Node(treewidget.Node): - def doPaste(self,node_selected): - objet_a_copier = self.item.get_copie_objet() - child=node_selected.doPaste_MCF(objet_a_copier) - #print "doPaste",child - return child - - def doPaste_MCF(self,objet_a_copier): - if self.item.isMCList() : - # le noeud courant est une MCList - child = self.append_child(objet_a_copier,pos='first',retour='oui') - #child = self.parent.append_child(objet_a_copier,pos='first',retour='oui') - elif self.item.isMCFact() : - # le noeud courant est un MCFACT - if self.parent.item.isMCList(): - # le noeud selectionne est un MCFACT dans une MCList - child = self.parent.append_child(objet_a_copier, - pos=self.item, - retour='oui') - else: - # le noeud MCFACT selectionne n'est pas dans une MCList - child = self.parent.append_child(objet_a_copier,retour='oui') - else: - showinfo("Copie impossible", - "Vous ne pouvez coller le mot-clé facteur copié à ce niveau de l'arborescence !") - self.appli.affiche_infos("Copie refusée") - child=None - #print "doPaste_MCF",child - return child - -class MCListTreeItem(Objecttreeitem.SequenceTreeItem,compofact.FACTTreeItem): - """ La classe MCListTreeItem joue le role d'un adaptateur pour les objets - du noyau Accas instances de la classe MCLIST. - Elle adapte ces objets pour leur permettre d'etre intégrés en tant que - noeuds dans un arbre graphique (voir treewidget.py et ObjectTreeItem.py). - Cette classe délègue les appels de méthode et les accès - aux attributs à l'objet du noyau soit manuellement soit - automatiquement (voir classe Delegate et attribut object). - """ - itemNode=Node - - def init(self): - # Si l'objet Accas (MCList) a moins d'un mot cle facteur - # on utilise directement ce mot cle facteur comme delegue - self.updateDelegate() - - def updateDelegate(self): - if len(self._object) > 1: - self.setdelegate(self._object) - else: - self.setdelegate(self._object.data[0]) - - def panel(self,jdcdisplay,pane,node): - """ Retourne une instance de l'objet panneau associe a l'item (self) - Si la liste ne contient qu'un mot clé facteur, on utilise le panneau - FACTPanel. - Si la liste est plus longue on utilise le panneau MCLISTPanel. - """ - if len(self._object) > 1: - return MCLISTPanel(jdcdisplay,pane,node) - elif isinstance(self._object.data[0],ErrorObj): - return compoerror.ERRORPanel(jdcdisplay,pane,node) - else: - return compofact.FACTPanel(jdcdisplay,pane,node) - - def IsExpandable(self): - if len(self._object) > 1: - return Objecttreeitem.SequenceTreeItem.IsExpandable(self) - else: - return compofact.FACTTreeItem.IsExpandable(self) - - def GetSubList(self): - self.updateDelegate() - if len(self._object) <= 1: - self._object.data[0].alt_parent=self._object - return compofact.FACTTreeItem.GetSubList(self) - - liste=self._object.data - sublist=[None]*len(liste) - # suppression des items lies aux objets disparus - for item in self.sublist: - old_obj=item.getObject() - if old_obj in liste: - pos=liste.index(old_obj) - sublist[pos]=item - else: - pass # objets supprimes ignores - # ajout des items lies aux nouveaux objets - pos=0 - for obj in liste: - if sublist[pos] is None: - # nouvel objet : on cree un nouvel item - def setfunction(value, object=obj): - object=value - item = self.make_objecttreeitem(self.appli, obj.nom + " : ", obj, setfunction) - sublist[pos]=item - #Attention : on ajoute une information supplementaire pour l'actualisation de - # la validite. L'attribut parent d'un MCFACT pointe sur le parent de la MCLISTE - # et pas sur la MCLISTE elle meme ce qui rompt la chaine de remontee des - # informations de validite. alt_parent permet de remedier a ce defaut. - obj.alt_parent=self._object - pos=pos+1 - - self.sublist=sublist - return self.sublist - - def GetIconName(self): - if self._object.isvalid(): - return "ast-green-los" - elif self._object.isoblig(): - return "ast-red-los" - else: - return "ast-yel-los" - - def get_docu(self): - """ Retourne la clé de doc de l'objet pointé par self """ - return self.object.get_docu() - - def iscopiable(self): - if len(self._object) > 1: - return Objecttreeitem.SequenceTreeItem.iscopiable(self) - else: - return compofact.FACTTreeItem.iscopiable(self) - - def isMCFact(self): - """ - Retourne 1 si l'objet pointé par self est un MCFact, 0 sinon - """ - return len(self._object) <= 1 - - def isMCList(self): - """ - Retourne 1 si l'objet pointé par self est une MCList, 0 sinon - """ - return len(self._object) > 1 - - def get_copie_objet(self): - return self._object.data[0].copy() - - def additem(self,obj,pos): - #print "compomclist.additem",obj,pos - if len(self._object) <= 1: - return compofact.FACTTreeItem.additem(self,obj,pos) - - o= self.object.addentite(obj,pos) - return o - - def suppitem(self,item): - """ - Retire un objet MCFACT de la MCList (self.object) - """ - #print "compomclist.suppitem",item - obj=item.getObject() - if len(self._object) <= 1: - return compofact.FACTTreeItem.suppitem(self,item) - - if self.object.suppentite(obj): - if len(self._object) == 1: self.updateDelegate() - message = "Mot-clé " + obj.nom + " supprimé" - self.appli.affiche_infos(message) - return 1 - else: - self.appli.affiche_infos('Impossible de supprimer ce mot-clé') - return 0 - - -import Accas -objet = Accas.MCList - -def treeitem(appli,labeltext,object,setfunction): - """ Factory qui produit un objet treeitem adapte a un objet - Accas.MCList (attribut objet de ce module) - """ - return MCListTreeItem(appli,labeltext,object,setfunction) diff --git a/InterfaceTK/componiveau.py b/InterfaceTK/componiveau.py deleted file mode 100644 index 175a3e89..00000000 --- a/InterfaceTK/componiveau.py +++ /dev/null @@ -1,133 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== - -from Tkinter import * -import Pmw - -from Editeur import Objecttreeitem -import panels -import fontes -from Extensions import commentaire - -Fonte_Niveau = fontes.canvas_gras_italique -Fonte_Niveau_inactif = fontes.canvas_italique - -class NIVEAUPanel(panels.OngletPanel): - def init(self): - """ Initialise les frame des panneaux contextuels relatifs à un JDC """ - panneau=Pmw.PanedWidget(self,orient='horizontal') - panneau.add('left',min=0.4,max=0.6,size=0.5) - panneau.add('right',min=0.4,max=0.6,size=0.5) - panneau.pack(expand=1,fill='both') - self.bouton_com.pack_forget() - self.makeJDCPage(panneau.pane('left')) - self.enlevebind() - - -import treewidget -class Node(treewidget.Node):pass - - -class NIVEAUTreeItem(Objecttreeitem.ObjectTreeItem): - panel = NIVEAUPanel - itemNode=Node - - def isactif(self): - return self.object.isactif() - - def IsExpandable(self): - return 1 - - def GetLabelText(self): - """ Retourne 3 valeurs : - - le texte à afficher dans le noeud représentant l'item - - la fonte dans laquelle afficher ce texte - - la couleur du texte - """ - if self.isactif(): - fonte = Fonte_Niveau - else : - fonte = Fonte_Niveau_inactif - return self.labeltext,fonte,'#00008b' - - def GetIconName(self): - if self.isactif(): - if self.object.isvalid(): - return "ast-green-text" - else: - return "ast-red-text" - else: - return "ast-white-text" - - def keys(self): - if self.object.etapes_niveaux != []: - return range(len(self.object.etapes_niveaux)) - else: - return range(len(self.object.etapes)) - - def GetSubList(self): - sublist=[] - for key in self.keys(): - if self.object.etapes_niveaux != []: - liste = self.object.etapes_niveaux - else: - liste = self.object.etapes - try: - value = liste[key] - except KeyError: - continue - def setfunction(value, key=key, object=liste): - object[key] = value - item =self.make_objecttreeitem(self.appli,value.ident() + " : ", value, setfunction) - sublist.append(item) - return sublist - - def additem(self,name,pos): - if isinstance(name,Objecttreeitem.TreeItem) : - cmd=self.object.addentite(name.getObject(),pos) - else : - cmd = self.object.addentite(name,pos) - item = self.make_objecttreeitem(self.appli,cmd.nom + " : ", cmd) - return item - - def suppitem(self,item) : - # item = item de l'ETAPE à supprimer du JDC - # item.getObject() = ETAPE ou COMMENTAIRE - # self.object = JDC - itemobject=item.getObject() - if self.object.suppentite(itemobject): - if isinstance(item.object,commentaire.COMMENTAIRE): - message = "Commentaire supprimé" - else : - message = "Commande " + itemobject.nom + " supprimée" - self.appli.affiche_infos(message) - return 1 - else: - self.appli.affiche_infos("Pb interne : impossible de supprimer cet objet") - return 0 - - def GetText(self): - return '' - - -import Accas -treeitem = NIVEAUTreeItem -objet = Accas.ETAPE_NIVEAU diff --git a/InterfaceTK/componuplet.py b/InterfaceTK/componuplet.py deleted file mode 100644 index 65b7afd9..00000000 --- a/InterfaceTK/componuplet.py +++ /dev/null @@ -1,175 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -# Modules Python -import types -import Tkinter -import Pmw -from repr import Repr -from copy import copy,deepcopy - -# Modules Eficas -from Editeur import Objecttreeitem -import panels - -# -__version__="$Name: $" -__Id__="$Id: componuplet.py,v 1.1.2.1 2007-08-10 13:59:00 pnoyret Exp $" -# - -myrepr = Repr() -myrepr.maxstring = 100 -myrepr.maxother = 100 - -# Si Expandable vaut 1 les éléments du nuplet apparaissent dans l'arbre -# Si Expandable vaut 0 les éléments n'apparaissent pas -Expandable=1 - -class NUPLETPanel(panels.OngletPanel): - def init(self): - """ Initialise les frame des panneaux contextuels relatifs \340 un NUPLET """ - self.nb=Pmw.NoteBook(self,raisecommand=self.raisecmd) - self.nb.pack(fill = 'both', expand = 1) - self.nb.add("Valeurs",tab_text="Saisir valeurs") - self.makeValeurPage(self.nb.page('Valeurs')) - self.enlevebind() - self.creebind() - self.nb.setnaturalsize() - - def makeValeurPage(self,page): - label = Tkinter.Label(page,text='Valeurs :').pack(side=Tkinter.LEFT) - i=0 - for obj in self.node.item.object.mc_liste: - frame_valeur=Tkinter.Frame(page) - frame_valeur.pack(side=Tkinter.LEFT) - if hasattr(obj,'definition'): - objet_mc=obj.definition - else: - objet_mc=None - valeur=obj.valeur - if type(valeur) == types.InstanceType : - valeur=obj.getval() - aide=self.gen_aide(obj) - if objet_mc.into != None : - l_choix=list(objet_mc.into) - #obj.set_valeur(l_choix[0],evaluation='non') - obj.set_valeur(l_choix[0]) - option=Pmw.OptionMenu (frame_valeur, - items = l_choix, - menubutton_width = 10, - command = lambda e,obj=obj,s=self:s.record_valeur(val=e,obj=obj), - ) - option.pack(side=Tkinter.LEFT,padx=1) - else : - entry = Tkinter.Entry(frame_valeur,relief='sunken',width=10) - entry.pack(side=Tkinter.LEFT,padx=1) - entry.bind("", - lambda e,obj=obj,s=self:s.valid_valeur(e,obj=obj)) - entry.bind("", - lambda e,obj=obj,s=self:s.valid_valeur(e,obj=obj)) - if i==0:entry.focus_set() - #aide = Tkinter.Label(frame_valeur, text = aide) - #aide.place(relx=0.5,rely=0.55,anchor='n') - if valeur != None : - entry.delete(0,Tkinter.END) - entry.insert(0,obj.getval()) - i=i+1 - - def record_valeur(self,val=None,obj=None,mess='Valeur du mot-cl\351 enregistr\351e'): - """ - Enregistre val comme valeur de self.node.item.object SANS faire de - test de validité - """ - #obj.set_valeur(val,evaluation='non') - obj.set_valeur(val) - self.parent.appli.affiche_infos(mess) - #self.node.parent.verif() - #self.node.update() - - def valid_valeur(self,e,obj=None,mess='Valeur du mot-cl\351 enregistr\351e'): - """ - Enregistre val comme valeur de self.node.item.object avec - test de validité - """ - valeur=e.widget.get() - e.widget.delete(0,Tkinter.END) - anc_val=obj.getval() - if anc_val == None:anc_val='' - test=obj.set_valeur(valeur) - if test: - if obj.isvalid(): - self.parent.appli.affiche_infos('Valeur du mot-cl\351 enregistr\351e') - e.widget.insert(0,obj.getval()) - else: - #obj.set_valeur(anc_val,evaluation='non') - obj.set_valeur(anc_val) - self.parent.appli.affiche_infos("valeur du mot-cl\351 non autoris\351e") - e.widget.insert(0,anc_val) - else: - print "impossible d'\351valuer : %s " %valeur - print "test =",test - self.parent.appli.affiche_infos("valeur du mot-cl\351 non autoris\351e") - e.widget.delete(0,Tkinter.END) - e.widget.insert(0,anc_val) - - #self.node.parent.verif() - #self.node.update() - - def gen_aide(self,obj): - return "" - - -class NUPLETTreeItem(Objecttreeitem.ObjectTreeItem): - panel=NUPLETPanel - - def IsExpandable(self): - return Expandable - - def GetText(self): - return '' - - def isvalid(self): - return self.object.isvalid() - - def GetIconName(self): - if self.object.isvalid(): - return "ast-green-los" - elif self.object.isoblig(): - return "ast-red-los" - else: - return "ast-yel-los" - - def GetSubList(self): - if not Expandable:return [] - sublist=[] - for obj in self.object.mc_liste: - item = self.make_objecttreeitem(self.appli, obj.nom + " : ", obj, None) - sublist.append(item) - return sublist - - def additem(self,name,pos): - raise "NUPLET" - - def suppitem(self,item) : - raise "NUPLET" - -import Accas -treeitem=NUPLETTreeItem -objet=Accas.MCNUPLET diff --git a/InterfaceTK/compooper.py b/InterfaceTK/compooper.py deleted file mode 100644 index 0575053d..00000000 --- a/InterfaceTK/compooper.py +++ /dev/null @@ -1,332 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -from Tkinter import * -import Pmw -import traceback -from Editeur import Objecttreeitem -import panels -import fontes - -class OPERPanel(panels.OngletPanel): - - def init(self): - nb = Pmw.NoteBook(self,raisecommand=self.raisecmd) - nb.pack(fill = 'both', expand = 1) - self.nb=nb - nb.add('Mocles', tab_text='Nouveau mot-clé') - nb.add('Concept', tab_text='Nommer concept') - nb.add('Commande', tab_text='Nouvelle Commande') - nb.add('Commentaire',tab_text='Paramètre/Commentaire') - panneau=Pmw.PanedWidget(nb.page("Mocles"), - orient='horizontal') - panneau.add('left',min=0.4,max=0.60,size=0.50) - panneau.add('right',min=0.4,max=0.60,size=0.50) - panneau.pack(expand=1,fill='both') - panneau.setnaturalsize() - self.makeCommandePage(nb.page("Commande")) - self.makeConceptPage_oper(nb.page("Concept")) - self.makeMoclesPage(panneau.pane('left')) - self.makeReglesPage(panneau.pane('right')) - #self.makeCommentairePage(nb.page("Commentaire")) - self.makeParamCommentPage_for_etape(nb.page("Commentaire")) - nb.tab('Mocles').focus_set() - self.nb.setnaturalsize() - self.enlevebind() - self.creebind() - self.affiche() - - def makeConceptPage_oper(self,page): - """ Crée la page de saisie du nom du concept """ - if self.node.item.is_reentrant(): - # commande obligatoirement reentrante - self.makeConceptPage_reentrant(page) - else: - # commande non reentrante ou facultativement reentrante - self.makeConceptPage(page) - - def makeConceptPage_reentrant(self,page): - """ Crée la page de saisie du nom de concept pour un opérateur reentrant - cad propose dans la liste des SD utilisées dans la commande celle(s) dont le - type est compatible avec celui que retourne l'opérateur """ - liste_noms_sd = self.node.item.get_noms_sd_oper_reentrant() - self.listbox = Pmw.ScrolledListBox(page, - items=liste_noms_sd, - labelpos='n', - label_text="Structure(s) de données à enrichir par l'opérateur courant :", - listbox_height = 6, - selectioncommand=self.select_valeur_from_list, - dblclickcommand=lambda s=self,c=self.execConcept : s.choose_valeur_from_list(c)) - self.listbox.place(relx=0.5,rely=0.3,relheight=0.4,anchor='center') - Label(page,text='Structure de donnée choisie :').place(relx=0.05,rely=0.6) - self.valeur_choisie = StringVar() - self.label_valeur = Label(page,textvariable=self.valeur_choisie) - self.label_valeur.place(relx=0.45,rely=0.6) - if len(liste_noms_sd) == 1 : - self.valeur_choisie.set(liste_noms_sd[0]) - - def select_valeur_from_list(self): - try: - choix = self.listbox.getcurselection()[0] - self.valeur_choisie.set(choix) - except: - traceback.print_exc() - - - def choose_valeur_from_list(self,command): - try: - choix = self.listbox.getcurselection()[0] - self.valeur_choisie.set(choix) - apply(command,(),{}) - except: - traceback.print_exc() - -import treewidget -class Node(treewidget.Node): - def doPaste(self,node_selected): - """ - Déclenche la copie de l'objet item avec pour cible - l'objet passé en argument : node_selected - """ - objet_a_copier = self.item.get_copie_objet() - child=node_selected.doPaste_Commande(objet_a_copier) - return child - - def doPaste_Commande(self,objet_a_copier): - """ - Réalise la copie de l'objet passé en argument qui est nécessairement - une commande - """ - parent=self.parent - #child = parent.item.append_child(objet_a_copier,self.item.getObject()) - child = self.append_brother(objet_a_copier,retour='oui') - #if child is None:return 0 - return child - - def doPaste_MCF(self,objet_a_copier): - """ - Réalise la copie de l'objet passé en argument (objet_a_copier) - Il s'agit forcément d'un mot clé facteur - """ - child = self.append_child(objet_a_copier,pos='first',retour='oui') - return child - - -class EtapeTreeItem(Objecttreeitem.ObjectTreeItem): - """ La classe EtapeTreeItem est un adaptateur des objets ETAPE du noyau - Accas. Elle leur permet d'etre affichés comme des noeuds - d'un arbre graphique. - Cette classe a entre autres deux attributs importants : - - _object qui est un pointeur vers l'objet du noyau - - object qui pointe vers l'objet auquel sont délégués les - appels de méthode et les accès aux attributs - Dans le cas d'une ETAPE, _object et object pointent vers le - meme objet. - """ - panel = OPERPanel - itemNode=Node - - def IsExpandable(self): - return 1 - - def GetIconName(self): - """ - Retourne le nom de l'icône à afficher dans l'arbre - Ce nom dépend de la validité de l'objet - """ - if not self.object.isactif(): - return "ast-white-square" - elif self.object.isvalid(): - return "ast-green-square" - else: - valid=self.valid_child() - valid=valid * self.valid_regles("non") - if self.reste_val != {}: - valid=0 - if valid==0 : - return "ast-red-square" - else : - return "ast-yellow-square" - - def GetLabelText(self): - """ Retourne 3 valeurs : - - le texte à afficher dans le noeud représentant l'item - - la fonte dans laquelle afficher ce texte - - la couleur du texte - """ - if self.object.isactif(): - # None --> fonte et couleur par défaut - return self.labeltext,None,None - else: - return self.labeltext,fontes.standard_italique,None - - def get_objet(self,name) : - for v in self.object.mc_liste: - if v.nom == name : return v - return None - - def get_type_sd_prod(self): - """ - Retourne le nom du type du concept résultat de l'étape - """ - sd_prod=self.object.get_type_produit() - if sd_prod: - return sd_prod.__name__ - else: - return "" - - def additem(self,name,pos): - #print "compooper.additem",name,pos - mcent = self._object.addentite(name,pos) - return mcent - - def suppitem(self,item) : - # item : item du MOCLE de l'ETAPE à supprimer - # item.getObject() = MCSIMP, MCFACT, MCBLOC ou MCList - itemobject=item.getObject() - if itemobject.isoblig() : - self.appli.affiche_infos('Impossible de supprimer un mot-clé obligatoire ') - return 0 - if self.object.suppentite(itemobject): - message = "Mot-clé " + itemobject.nom + " supprimé" - self.appli.affiche_infos(message) - return 1 - else : - self.appli.affiche_infos('Pb interne : impossible de supprimer ce mot-clé') - return 0 - - def GetText(self): - try: - return self.object.get_sdname() - except: - return '' - - def keys(self): - keys=self.object.mc_dict.keys() - return keys - - def GetSubList(self): - """ - Reactualise la liste des items fils stockes dans self.sublist - """ - if self.isactif(): - liste=self.object.mc_liste - else: - liste=[] - - sublist=[None]*len(liste) - # suppression des items lies aux objets disparus - for item in self.sublist: - old_obj=item.getObject() - if old_obj in liste: - pos=liste.index(old_obj) - sublist[pos]=item - else: - pass # objets supprimes ignores - - # ajout des items lies aux nouveaux objets - pos=0 - for obj in liste: - if sublist[pos] is None: - # nouvel objet : on cree un nouvel item - def setfunction(value, object=obj): - object.setval(value) - item = self.make_objecttreeitem(self.appli, obj.nom + " : ", obj, setfunction) - sublist[pos]=item - pos=pos+1 - - self.sublist=sublist - return self.sublist - - def isvalid(self): - return self.object.isvalid() - - def iscopiable(self): - """ - Retourne 1 si l'objet est copiable, 0 sinon - """ - return 1 - - def update(self,item): - if item.sd and item.sd.nom: - self.nomme_sd(item.sd.nom) - - def nomme_sd(self,nom): - """ Lance la méthode de nommage de la SD """ - oldnom="" - if self.object.sd != None : - oldnom=self.object.sd.nom - test,mess= self.object.nomme_sd(nom) - if test:self.object.parent.reset_context() - if (test and self.appli.dict_reels.has_key(oldnom) ): - self.appli.dict_reels[nom]=self.appli.dict_reels[oldnom] - return test,mess - - def is_reentrant(self): - return self.object.is_reentrant() - - def get_noms_sd_oper_reentrant(self): - return self.object.get_noms_sd_oper_reentrant() - - def get_objet_commentarise(self): - """ - Cette méthode retourne un objet commentarisé - représentatif de self.object - """ - # Format de fichier utilisé - format=self.appli.format_fichier.get() - return self.object.get_objet_commentarise(format) - - def get_objet_commentarise_BAK(self): - """ - Cette méthode retourne un objet commentarisé - représentatif de self.object - """ - import generator,string,Accas - # Format de fichier utilisé - format=self.appli.format_fichier.get() - g=generator.plugins[format]() - texte_commande = g.gener(self.object,format='beautifie') - # Il faut enlever la première ligne vide de texte_commande que - # rajoute le generator - rebut,texte_commande = string.split(texte_commande,'\n',1) - # on construit l'objet COMMANDE_COMM repésentatif de self mais non - # enregistré dans le jdc - commande_comment = Accas.COMMANDE_COMM(texte=texte_commande,reg='non', - parent=self.object.parent) - commande_comment.niveau = self.object.niveau - commande_comment.jdc = commande_comment.parent = self.object.jdc - - pos=self.object.parent.etapes.index(self.object) - parent=self.object.parent - self.object.parent.suppentite(self.object) - parent.addentite(commande_comment,pos) - - return commande_comment - - def visu_3D(self,appli,node) : - import TroisDPal - troisD=TroisDPal.TroisDPilote(node.item,appli,node.parent) - troisD.envoievisu() - -import Accas -treeitem = EtapeTreeItem -objet = Accas.ETAPE - diff --git a/InterfaceTK/compoparam.py b/InterfaceTK/compoparam.py deleted file mode 100644 index 80094ad3..00000000 --- a/InterfaceTK/compoparam.py +++ /dev/null @@ -1,248 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -""" - Ce module contient les classes permettant de définir les objets graphiques - représentant un objet de type PARAMETRE, cad le panneau et l'item de l'arbre - d'EFICAS -""" - -# import modules Python -from Tkinter import * -import Pmw -import string - -# import modules EFICAS -from Editeur import Objecttreeitem -import panels -import fontes - - -Fonte_PARAMETRE = fontes.standard_italique -Fonte_TITRE = fontes.standard_gras_souligne - - -class PARAMPanel(panels.OngletPanel): - """ - Classe servant à construire le panneau associé à un paramètre. - C'est au moyen de ce panneau que l'utilisateur peut accéder - aux nom et valeur du paramètre en vue éventuellement de les - modifier. - """ - - def init(self): - """ - Initialise les frame des panneaux contextuels relatifs à un PARAMETRE - """ - nb = Pmw.NoteBook(self,raisecommand=self.raisecmd) - nb.pack(fill = 'both', expand = 1) - self.nb=nb - nb.add('Parametre', tab_text='Valeur Paramètre') - nb.add('Commande', tab_text='Nouvelle Commande') - nb.add('Commentaire',tab_text='Paramètre/Commentaire') - self.makeParametrePage(nb.page("Parametre")) - self.makeCommandePage(nb.page("Commande")) - self.makeParamCommentPage_for_etape(nb.page("Commentaire")) - nb.tab('Parametre').focus_set() - nb.setnaturalsize() - self.make_buttons() - self.enlevebind() - self.creebind() - - def makeParametrePage(self,page): - """ - Crée la page qui permet d'afficher et d'éditer le texte du PARAMETRE - """ - self.frame_valeur = Frame(page) - #self.frame_valeur.place(relwidth=0.9,relheight=0.9,relx=0.05,rely=0.05,anchor='nw') - self.frame_valeur.pack(expand=1) - # affichage du titre du panneau - self.titre = StringVar() - self.titre.set("PARAMETRE "+self.node.item.get_nom()) - #Label(self.frame_valeur,textvariable=self.titre,font=Fonte_TITRE).place(relx=0.5,rely=0.1,anchor='n') - Label(self.frame_valeur,textvariable=self.titre,font=Fonte_TITRE).grid(row=0,columnspan=2,padx=5,pady=5) - # création des labels et entries associés aux nom et valeur du paramètre - #Label(self.frame_valeur,text= 'Nom du paramètre : ').place(relx=0.,rely=0.3) - Label(self.frame_valeur,text= 'Nom du paramètre : ').grid(row=1,sticky=W,padx=5,pady=5) - self.entry_nom = Entry(self.frame_valeur) - #Label(self.frame_valeur,text= 'Valeur du paramètre : ').place(relx=0.,rely=0.5) - Label(self.frame_valeur,text= 'Valeur du paramètre : ').grid(row=2,sticky=W,padx=5,pady=5) - self.entry_val = Entry(self.frame_valeur) - # binding sur entry_nom - self.entry_nom.bind("",lambda e,s=self : s.entry_val.focus()) - self.entry_val.bind("",lambda e,s=self : s.change_valeur()) - self.entry_nom.bind("",lambda e,s=self : s.entry_val.focus()) - self.entry_val.bind("",lambda e,s=self : s.change_valeur()) - # affichage des entries - #self.entry_nom.place(relx=0.35,rely=0.3,relwidth=0.3) - self.entry_nom.grid(row=1,column=1,sticky=W,padx=5,pady=5) - #self.entry_val.place(relx=0.35,rely=0.5,relwidth=0.5) - self.entry_val.grid(row=2,column=1,sticky=W,padx=5,pady=5) - # affichage d'une phrase d'aide - aide = """ - Un retour de chariot dans une zone de saisie vous permet de vérifier si - la valeur que vous avez entrée est valide. - Ce n'est qu'après avoir appuyé sur le bouton Valider que les nouvelles - valeurs seront effectivement prises en compte - """ - #Label(self.frame_valeur,text=aide).place(relx=0.5,rely=0.65,anchor='n') - Label(self.frame_valeur,text=aide).grid(row=3,columnspan=2,padx=5,pady=5) - self.frame_valeur.columnconfigure(1,weight=1) - # affichage des nom et valeur du paramètre - self.display_valeur() - self.entry_nom.focus() - - def make_buttons(self): - """ - Crée les boutons du panneau - """ - #self.bouton_sup.place_forget() - #self.bouton_doc.place_forget() - #self.bouton_val = Button(self.fr_but,text='Valider',command=self.change_valeur,width=14) - #self.bouton_ann = Button(self.fr_but,text='Annuler',command=self.display_valeur,width=14) - #self.bouton_val.place(relx=0.25,rely=0.5,relheight=0.8,anchor='center') - #self.bouton_ann.place(relx=0.50,rely=0.5,relheight=0.8,anchor='center') - #self.bouton_sup.place(relx=0.75,rely=0.5,relheight=0.8,anchor='center') - - self.bouton_sup.pack_forget() - self.bouton_doc.pack_forget() - self.bouton_val = Button(self.fr_but,text='Valider',command=self.change_valeur) - self.bouton_ann = Button(self.fr_but,text='Annuler',command=self.display_valeur) - self.bouton_val.pack(side='left',padx=5, pady=5) - self.bouton_ann.pack(side='left',padx=5, pady=5) - self.bouton_sup.pack(side='right',padx=5, pady=5) - - def change_valeur(self): - """ - Stocke la nouvelle valeur donnée par l'utilisateur comme valeur du PARAMETRE - """ - if self.parent.modified == 'n' : self.parent.init_modif() - new_nom = self.entry_nom.get() - new_val = self.entry_val.get() - self.node.item.set_nom(new_nom) - self.node.item.set_valeur(new_val) - self.node.update() - self.display_valeur() - - def display_valeur(self): - """ - Affiche dans self.widget_text la valeur de l'objet PARAMETRE - (annule d'éventuelles modifications faite par l'utilisateur) - """ - self.entry_nom.delete(0,END) - self.entry_val.delete(0,END) - self.titre.set('PARAMETRE '+self.node.item.get_nom()) - self.entry_nom.insert(END,self.node.item.get_nom()) - self.entry_val.insert(END,self.node.item.get_valeur()) - -class PARAMTreeItem(Objecttreeitem.ObjectTreeItem): - """ - Classe servant à définir l'item porté par le noeud de l'arbre d'EFICAS - qui représente le PARAMETRE - """ - panel = PARAMPanel - - def init(self): - self.setfunction = self.set_valeur - -# --------------------------------------------------------------------------- -# API du PARAMETRE pour l'arbre -# --------------------------------------------------------------------------- - - def GetIconName(self): - """ - Retourne le nom de l'icône associée au noeud qui porte self, - dépendant de la validité de l'objet - NB : un PARAMETRE est toujours valide ... - """ - if self.isactif(): - if self.isvalid(): - return "ast-green-square" - else: - return "ast-red-square" - else: - return "ast-white-square" - - def GetLabelText(self): - """ Retourne 3 valeurs : - - le texte à afficher dans le noeud représentant l'item - - la fonte dans laquelle afficher ce texte - - la couleur du texte - """ - return 'Paramètre',Fonte_PARAMETRE,None - - def GetText(self): - """ - Retourne le texte à afficher après le nom de la commande (ici après 'paramètre') - Ce texte est tronqué à 25 caractères - """ - texte = repr(self.object) - texte = string.split(texte,'\n')[0] - if len(texte) < 25 : - return texte - else : - return texte[0:24]+'...' - - def GetSubList(self): - """ - Retourne la liste des fils de self - """ - return [] - -# --------------------------------------------------------------------------- -# Méthodes permettant la modification et la lecture des attributs -# du paramètre = API graphique du PARAMETRE pour Panel et EFICAS -# --------------------------------------------------------------------------- - - def get_valeur(self): - """ - Retourne la valeur de l'objet PARAMETRE cad son texte - """ - if self.object.valeur is None: return '' - else: return self.object.valeur - - def get_nom(self): - """ - Retourne le nom du paramètre - """ - return self.object.nom - - def set_valeur(self,new_valeur): - """ - Affecte valeur à l'objet PARAMETRE - """ - self.object.set_valeur(new_valeur) - - def set_nom(self,new_nom): - """ - Renomme le paramètre - """ - self.object.set_nom(new_nom) - #self.object.set_attribut('nom',new_nom) - - def get_fr(self): - """ - Retourne le fr associé au paramètre, cad la bulle d'aide pour EFICAS - """ - return "Définition d'un paramètre" - -import Extensions.parametre -treeitem =PARAMTreeItem -objet = Extensions.parametre.PARAMETRE diff --git a/InterfaceTK/compoparameval.py b/InterfaceTK/compoparameval.py deleted file mode 100644 index 009473d4..00000000 --- a/InterfaceTK/compoparameval.py +++ /dev/null @@ -1,311 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -""" -Ce module contient les classes permettant de définir les objets graphiques -représentant un objet de type PARAMETRE_EVAL, cad le panneau et l'item de l'arbre -d'EFICAS -""" - -# import modules Python -from Tkinter import * -import Pmw -import string - -# import modules EFICAS -import widgets -from Editeur import Objecttreeitem -import panels -import fontes - - -Fonte_PARAMETRE = fontes.standard_italique -Fonte_TITRE = fontes.standard_gras_souligne - - -class PARAM_EVALPanel(panels.OngletPanel): - """ - Classe servant à construire le panneau associé à un paramètre. - C'est au moyen de ce panneau que l'utilisateur peut accéder - aux nom et valeur du paramètre en vue éventuellement de les - modifier. - """ - - def init(self): - """ - Initialise les frame des panneaux contextuels relatifs à un PARAMETRE - """ - nb = Pmw.NoteBook(self,raisecommand=self.raisecmd) - nb.pack(fill = 'both', expand = 1) - self.nb=nb - nb.add('Parametre', tab_text='Paramètre EVAL') - nb.add('Commande', tab_text='Nouvelle Commande') - nb.add('Commentaire',tab_text='Paramètre/Commentaire') - self.makeParametrePage(nb.page("Parametre")) - self.makeCommandePage(nb.page("Commande")) - self.makeParamCommentPage_for_etape(nb.page("Commentaire")) - nb.tab('Parametre').focus_set() - nb.setnaturalsize() - self.make_buttons() - - def makeParametrePage(self,page): - """ - Crée la page qui permet d'afficher et d'éditer le texte du PARAMETRE - """ - self.frame_valeur = Frame(page) - self.frame_valeur.place(relwidth=0.9,relheight=0.9,relx=0.05,rely=0.05,anchor='nw') - # affichage du titre du panneau - self.titre = StringVar() - self.titre.set("PARAMETRE EVAL "+self.node.item.get_nom()) - Label(self.frame_valeur,textvariable=self.titre,font=Fonte_TITRE).place(relx=0.5,rely=0.1,anchor='n') - # création des labels et entries associés aux nom et valeur du paramètre - Label(self.frame_valeur,text= 'Nom du paramètre : ').place(relx=0.,rely=0.3) - self.entry_nom = Entry(self.frame_valeur) - Label(self.frame_valeur,text= 'Valeur du paramètre : ').place(relx=0.,rely=0.5) - self.entry_val = Entry(self.frame_valeur) - # binding sur entry_nom - self.entry_nom.bind("",lambda e,s=self : s.verif_nom()) - self.entry_val.bind("",lambda e,s=self : s.verif_eval()) - self.entry_nom.bind("",lambda e,s=self : s.verif_nom()) - self.entry_val.bind("",lambda e,s=self : s.verif_eval()) - # affichage des entries - self.entry_nom.place(relx=0.35,rely=0.3,relwidth=0.3) - self.entry_val.place(relx=0.35,rely=0.5,relwidth=0.5) - # affichage d'une phrase d'aide - aide = """ - Un retour de chariot dans une zone de saisie vous permet de vérifier si - la valeur que vous avez entrée est valide. - Ce n'est qu'après avoir appuyé sur le bouton Valider que les nouvelles - valeurs seront effectivement prises en compte - """ - Label(self.frame_valeur,text=aide).place(relx=0.5,rely=0.65,anchor='n') - # affichage des nom et valeur du paramètre - self.display_valeur() - self.entry_nom.focus() - - def make_buttons(self): - """ - Crée les boutons du panneau - """ - #self.bouton_sup.place_forget() - #self.bouton_doc.place_forget() - self.bouton_sup.pack_forget() - self.bouton_doc.pack_forget() - #self.bouton_val = Button(self.fr_but,text='Valider',command=self.change_valeur,width=14) - #self.bouton_ann = Button(self.fr_but,text='Annuler',command=self.display_valeur,width=14) - self.bouton_val = Button(self.fr_but,text='Valider',command=self.change_valeur) - self.bouton_ann = Button(self.fr_but,text='Annuler',command=self.display_valeur) - self.bouton_val.bind("",lambda e,s=self : s.bouton_val.invoke()) - self.bouton_val.bind("",lambda e,s=self : s.bouton_val.invoke()) - #self.bouton_val.place(relx=0.25,rely=0.5,relheight=0.8,anchor='center') - #self.bouton_ann.place(relx=0.50,rely=0.5,relheight=0.8,anchor='center') - #self.bouton_sup.place(relx=0.75,rely=0.5,relheight=0.8,anchor='center') - self.bouton_val.pack(side='left',padx=5, pady=5) - self.bouton_ann.pack(side='left',padx=5, pady=5) - self.bouton_sup.pack(side='left',padx=5, pady=5) - - def change_valeur(self): - """ - Stocke la nouvelle valeur donnée par l'utilisateur comme valeur du PARAMETRE - """ - if self.parent.modified == 'n' : self.parent.init_modif() - new_nom = self.entry_nom.get() - new_val = self.entry_val.get() - #self.node.item.set_nom(new_nom) - #self.node.item.set_valeur(new_val) - #self.node.update() - #self.display_valeur() - # on essaie de stocker les noms et valeurs - test,erreur = self.node.item.save_parametre_eval(new_nom,new_val) - if test : - # on a pu stocker les nouveaux paramètres : il faut rafraîchir l'affichage - self.node.update() - self.display_valeur() - self.parent.appli.affiche_infos("Expression EVAL %s modifiée" %self.node.item.get_nom()) - else: - # la formule est incorrecte : on affiche les erreurs - widgets.showerror("Expression EVAL incorrecte",erreur) - self.parent.appli.affiche_infos("Expression EVAL %s non modifiée" %self.node.item.get_nom()) - - def display_valeur(self): - """ - Affiche dans self.widget_text la valeur de l'objet PARAMETRE - (annule d'éventuelles modifications faite par l'utilisateur) - """ - self.entry_nom.delete(0,END) - self.entry_val.delete(0,END) - self.titre.set('PARAMETRE '+self.node.item.get_nom()) - self.entry_nom.insert(END,self.node.item.get_nom()) - self.entry_val.insert(END,self.node.item.get_valeur()) - - def verif_nom(self): - """ - Lance la vérification du nom donné par l'utilisateur dans entry_nom - """ - nom = self.entry_nom.get() - test,erreur = self.node.item.verif_nom(nom) - if not test : - widgets.showerror("Nom invalide",erreur) - self.entry_nom.focus() - self.entry_nom.selection_range(0,END) - self.parent.appli.affiche_infos("Nom du paramètre refusé") - else: - self.parent.appli.affiche_infos("Nom du paramètre accepté") - - def verif_eval(self,event=None): - """ - Lance la vérification de l'expression EVAL présente dans entry_val - """ - exp_eval = self.entry_val.get() - test,erreur = self.node.item.verif_eval(exp_eval) - if not test: - widgets.showerror("Expression EVAL invalide",erreur) - self.entry_val.focus() - self.entry_val.selection_range(0,END) - self.parent.appli.affiche_infos("Expression EVAL refusée") - else: - self.parent.appli.affiche_infos("Expression EVAL acceptée") - -class PARAM_EVALTreeItem(Objecttreeitem.ObjectTreeItem): - """ - Classe servant à définir l'item porté par le noeud de l'arbre d'EFICAS - qui représente le PARAMETRE - """ - panel = PARAM_EVALPanel - - def init(self): - self.setfunction = self.set_valeur - -# --------------------------------------------------------------------------- -# API du PARAMETRE pour l'arbre -# --------------------------------------------------------------------------- - - def GetIconName(self): - """ - Retourne le nom de l'icône associée au noeud qui porte self, - dépendant de la validité de l'objet - NB : un PARAMETRE est toujours valide ... - """ - if self.isactif(): - if self.isvalid(): - return "ast-green-square" - else: - return "ast-red-square" - else: - return "ast-white-square" - - def GetLabelText(self): - """ Retourne 3 valeurs : - - le texte à afficher dans le noeud représentant l'item - - la fonte dans laquelle afficher ce texte - - la couleur du texte - """ - return 'EVAL',Fonte_PARAMETRE,None - - def GetText(self): - """ - Retourne le texte à afficher après le nom de la commande (ici après 'paramètre') - Ce texte est tronqué à 25 caractères - """ - texte = repr(self.object) - texte = string.split(texte,'\n')[0] - if len(texte) < 25 : - return texte - else : - return texte[0:24]+'...' - - def GetSubList(self): - """ - Retourne la liste des fils de self - """ - return [] - -# --------------------------------------------------------------------------- -# Méthodes permettant la modification et la lecture des attributs -# du paramètre = API graphique du PARAMETRE pour Panel et EFICAS -# --------------------------------------------------------------------------- - - def isvalid(self): - """ - Indique si l'objet pointé par self est valide - """ - return self.object.isvalid() - - def get_valeur(self): - """ - Retourne une chaîne représentant la valeur de l'objet PARAMETRE - cad de l'objet class_eval.EVAL - """ - return self.object.get_valeur() or '' - - def get_nom(self): - """ - Retourne le nom du paramètre - """ - return self.object.get_nom() - - def set_valeur(self,new_valeur): - """ - Affecte new_valeur à l'objet PARAMETRE_EVAL - """ - # on construit le texte de la nouvelle valeur - new_valeur = 'EVAL("""'+new_valeur+'""")' - # on affecte la nouvelle valeur à self.object - self.object.set_valeur(new_valeur) - - def set_nom(self,new_nom): - """ - Renomme le paramètre - """ - self.object.set_nom(new_nom) - - def get_fr(self): - """ - Retourne le fr associé au paramètre, cad la bulle d'aide pour EFICAS - """ - return "Définition d'un paramètre de type EVAL" - - def verif_nom(self,nom): - """ - Lance la vérification de validité du nom passé en argument - """ - return self.object.verif_nom(nom = nom) - - def verif_eval(self,valeur): - """ - Lance la vérification de validité de l'expression EVAL passée en argument - """ - return self.object.verif_eval(exp_eval = valeur) - - def save_parametre_eval(self,new_nom,new_val): - """ - Vérifie si (new_nom,new_val) définit bien un EVAL licite : - - si oui, stocke ces paramètres comme nouveaux paramètres de l'EVAL courant et retourne 1 - - si non, laisse les paramètres anciens de EVAL inchangés et retourne 0 - """ - test,erreur = self.object.verif_parametre_eval(param=(new_nom,new_val)) - if test : - # la formule est bien correcte : on sauve les nouveaux paramètres - self.object.update(param=(new_nom,new_val)) - return test,erreur - -import Extensions.parametre_eval -treeitem =PARAM_EVALTreeItem -objet = Extensions.parametre_eval.PARAMETRE_EVAL diff --git a/InterfaceTK/compoproc.py b/InterfaceTK/compoproc.py deleted file mode 100644 index 3d3e906e..00000000 --- a/InterfaceTK/compoproc.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -from Tkinter import * -import Pmw - -from Editeur import Objecttreeitem -import panels -import fontes -import compooper - -class PROCPanel(panels.OngletPanel): - def init(self): - nb = Pmw.NoteBook(self,raisecommand=self.raisecmd) - self.nb=nb - nb.pack(fill = 'both', expand = 1) - nb.add('Mocles', tab_text='Ajouter mots-clés') - nb.add('Commande', tab_text='Nouvelle Commande') - nb.add('Commentaire',tab_text='Paramètre/Commentaire') - panneau=Pmw.PanedWidget(nb.page("Mocles"), - orient='horizontal') - panneau.add('left',min=0.4,max=0.6,size=0.5) - panneau.add('right',min=0.4,max=0.6,size=0.5) - panneau.pack(expand=1,fill='both') - self.makeCommandePage(nb.page("Commande")) - self.makeMoclesPage(panneau.pane('left')) - self.makeReglesPage(panneau.pane('right')) - self.makeParamCommentPage_for_etape(nb.page("Commentaire")) - nb.setnaturalsize() - self.enlevebind() - self.creebind() - self.affiche() - -class ProcEtapeTreeItem(compooper.EtapeTreeItem): - panel = PROCPanel - -import Accas -treeitem = ProcEtapeTreeItem -objet = Accas.PROC_ETAPE - diff --git a/InterfaceTK/composimp.py b/InterfaceTK/composimp.py deleted file mode 100644 index d278c166..00000000 --- a/InterfaceTK/composimp.py +++ /dev/null @@ -1,652 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -# Modules Python -import string,types,os -from Tkinter import * -import Pmw -from copy import copy,deepcopy -import traceback - -# Modules Eficas -from Editeur import Objecttreeitem -import prefs -import panels -import images -from widgets import ListeChoix -from widgets import FenetreDeSelection - -from Noyau.N_CR import justify_text -from Editeur.utils import substract_list - - -class SIMPTreeItem(Objecttreeitem.AtomicObjectTreeItem): - from newsimppanel import newSIMPPanel - panel = newSIMPPanel - - def init(self) : - self.expandable = 0 - self.affect_panel() - - - def affect_panel(self): - """ - Cette méthode attribue le panel à l'objet pointé par self en fonction de la - nature de la valeur demandée pour cet objet - """ - from uniquepanel import UNIQUE_Panel - from plusieurspanel import PLUSIEURS_Panel - - #print "affect_panel : ",self.nom,self.is_list(),self.has_into() - # Attention l ordre des if est important - - if self.wait_shell(): - # l'objet attend un shell - from shellpanel import SHELLPanel - self.panel = SHELLPanel - elif self.has_into(): - # l'objet prend sa (ses) valeur(s) dans un ensemble discret de valeurs - if self.is_list() : - from plusieursintopanel import PLUSIEURS_INTO_Panel - self.panel = PLUSIEURS_INTO_Panel - else: - from uniqueintopanel import UNIQUE_INTO_Panel - self.panel = UNIQUE_INTO_Panel - else: - # l'objet prend une ou des valeurs à priori quelconques - if self.is_list() : - # on attend une liste de valeurs mais de quel type ? - if self.wait_assd(): - # on attend une liste de SD - from plusieursassdpanel import PLUSIEURS_ASSD_Panel - self.panel = PLUSIEURS_ASSD_Panel - else: - # on attend une liste de valeurs de types debase (entiers, réels,...) - #from plusieursbasepanel import PLUSIEURS_BASE_OR_UNELISTE_Panel - #self.panel = PLUSIEURS_BASE_OR_UNELISTE_Panel - from plusieursbasepanel import PLUSIEURS_BASE_Panel - self.panel = PLUSIEURS_BASE_Panel - else: - # on n'attend qu'une seule valeur mais de quel type ? - if self.wait_co(): - # on attend une SD ou un objet de la classe CO (qui n'existe pas encore) - from uniquesdcopanel import UNIQUE_SDCO_Panel - self.panel = UNIQUE_SDCO_Panel - elif self.wait_assd(): - # on attend une SD - from uniqueassdpanel import UNIQUE_ASSD_Panel - from uniqueassdpanel import UNIQUE_ASSD_Panel_Reel - if 'R' in self.GetType(): - self.panel = UNIQUE_ASSD_Panel_Reel - else : - self.panel = UNIQUE_ASSD_Panel - else: - # on attend une valeur d'un type de base (entier,réel,...) - if self.wait_complex(): - # on attend un complexe - from uniquecomppanel import UNIQUE_COMP_Panel - self.panel = UNIQUE_COMP_Panel - else: - # on attend un entier, un réel ou une string - from uniquebasepanel import UNIQUE_BASE_Panel - self.panel = UNIQUE_BASE_Panel - # cas particulier des fonctions - genea = self.get_genealogie() - if "VALE" in genea or "VALE_C" in genea: - if "DEFI_FONCTION" in genea : - from fonctionpanel import FONCTION_Panel - self.panel=FONCTION_Panel - #--------------------------------------------------------- - # PN ajout pour lancement de Salome - #--------------------------------------------------------- - if self.appli.salome: - import panelsSalome - - self.select_noeud_maille=0 - self.clef_fonction="SALOME" - for i in range(0,len( genea )) : - self.clef_fonction=self.clef_fonction+"_"+ genea[i] - #if genea[i] == "GROUP_NO" or genea[i] == "GROUP_MA": - if "GROUP_NO" in genea[len(genea)-1] or "GROUP_MA" in genea[len(genea)-1]: - self.select_noeud_maille=1 - - recherche=panelsSalome.dict_classes_salome[self.panel] - if hasattr(recherche,self.clef_fonction): - self.panel=recherche - if self.select_noeud_maille==1 : - self.panel=recherche - - - #----------------------------------------------- - # - # Methodes liees aux informations sur le Panel - # ou au mot-clef simple - # - #----------------------------------------------- - # is_list - # get_into a priori inutile --> commentee - # has_into - # wait_into a priori inutile --> commentee - # GetMinMax - # GetMultiplicite - # GetIntervalle - # GetListeValeurs - # get_liste_possible - - def is_list(self): - """ - Cette méthode indique si le mot cle simple attend une liste (valeur de retour 1) - ou s'il n'en attend pas (valeur de retour 0) - - Deux cas principaux peuvent se presenter : avec validateurs ou bien sans. - Dans le cas sans validateur, l'information est donnée par l'attribut max - de la definition du mot cle. - Dans le cas avec validateur, il faut combiner l'information précédente avec - celle issue de l'appel de la méthode is_list sur le validateur.On utilisera - l'operateur ET pour effectuer cette combinaison (AndVal). - """ - is_a_list=0 - min,max = self.GetMinMax() - assert (min <= max) - if max > 1 : - is_a_list=1 - # Dans le cas avec validateurs, pour que le mot cle soit considéré - # comme acceptant une liste, il faut que max soit supérieur a 1 - # ET que la méthode is_list du validateur retourne 1. Dans les autres cas - # on retournera 0 (n'attend pas de liste) - if self.definition.validators : - is_a_list= self.definition.validators.is_list() * is_a_list - return is_a_list - - #def get_into(self,liste_courante=None): - # """ - # Cette méthode retourne la liste de choix proposée par le mot cle. Si le mot cle ne propose - # pas de liste de choix, la méthode retourne None. - # L'argument d'entrée liste_courante, s'il est différent de None, donne la liste des choix déjà - # effectués par l'utilisateur. Dans ce cas, la méthode get_into doit calculer la liste des choix - # en en tenant compte. - # Cette méthode part du principe que la relation entre into du mot clé et les validateurs est - # une relation de type ET (AndVal). - # """ - # if not self.object.definition.validators : - # return self.object.definition.into - # else: - # return self.object.definition.validators.get_into(liste_courante,self.definition.into) - - def has_into(self): - """ - Cette méthode indique si le mot cle simple propose un choix (valeur de retour 1) - ou s'il n'en propose pas (valeur de retour 0) - - Deux cas principaux peuvent se presenter : avec validateurs ou bien sans. - Dans le cas sans validateur, l'information est donnée par l'attribut into - de la definition du mot cle. - Dans le cas avec validateurs, pour que le mot cle soit considéré - comme proposant un choix, il faut que into soit présent OU - que la méthode has_into du validateur retourne 1. Dans les autres cas - on retournera 0 (ne propose pas de choix) - """ - has_an_into=0 - if self.definition.into: - has_an_into=1 - elif self.definition.validators : - has_an_into= self.definition.validators.has_into() - return has_an_into - -# def wait_into(self): -# """ Méthode booléenne qui retourne 1 si l'objet pointé par self -# prend ses valeurs dans un ensemble discret (into), 0 sinon """ -# if self.object.definition.into != None : -# return 1 -# else: -# return 0 - - def GetMinMax(self): - """ Retourne les valeurs min et max de la définition de object """ - return self.object.get_min_max() - - def GetMultiplicite(self): - """ A préciser. - Retourne la multiplicité des valeurs affectées à l'objet - représenté par l'item. Pour le moment retourne invariablement 1. - """ - return 1 - - def GetIntervalle(self): - """ - Retourne le domaine de valeur attendu par l'objet représenté - par l'item. - """ - return self.object.getintervalle() - - def GetListeValeurs(self) : - """ Retourne la liste des valeurs de object """ - valeurs=self.object.get_liste_valeurs() - try : - if "R" in self.object.definition.type: - clef=self.object.GetNomConcept() - if self.appli.dict_reels.has_key(clef): - if type(valeurs) == types.TupleType: - valeurs_reelles=[] - for val in valeurs : - if self.appli.dict_reels[clef].has_key(val) : - valeurs_reelles.append(self.appli.dict_reels[clef][val]) - else : - valeurs_reelles.append(val) - else : - if self.appli.dict_reels[clef].has_key(valeurs): - valeurs_reelles=self.appli.dict_reels[clef][valeurs] - valeurs=valeurs_reelles - except : - pass - return valeurs - - def get_liste_possible(self,listeActuelle=[]): - if hasattr(self.definition.validators,'into'): - valeurspossibles = self.definition.validators.into - else: - valeurspossibles = self.get_definition().into - - #On ne garde que les items valides - listevalideitem=[] - for item in valeurspossibles: - encorevalide=self.valide_item(item) - if encorevalide : - listevalideitem.append(item) - - #on ne garde que les choix possibles qui passent le test de valide_liste_partielle - listevalideliste=[] - for item in listevalideitem: - encorevalide=self.valide_liste_partielle(item,listeActuelle) - if encorevalide : - listevalideliste.append(item) - return listevalideliste - - def get_liste_param_possible(self): - liste_param=[] - for param in self.object.jdc.params: - encorevalide=self.valide_item(param.valeur) - if encorevalide: - type_param=param.valeur.__class__.__name__ - for typ in self.definition.type: - if typ=='R': - liste_param.append(param) - if typ=='I' and type_param=='int': - liste_param.append(param) - if typ=='TXM' and type_param=='str': - liste_param.append(repr(param)) - return liste_param - - #-------------------------------------------------- - # - # Methodes liees a la validite des valeurs saisies - # - #--------------------------------------------------- - # valide_item - # valide_liste_partielle - # valide_liste_complete - # info_erreur_item - # info_erreur_liste - # IsInIntervalle - # isvalid - - def valide_item(self,item): - """ - La validation est réalisée directement par l'objet - """ - return self.object.valide_item(item) - - def valide_liste_partielle(self,item,listecourante): - #On protege la liste en entree en la copiant - valeur=listecourante[:] - valeur.append(item) - return self.object.valid_valeur_partielle(valeur) - - def valide_liste_complete (self,valeur): - return self.object.valid_valeur(valeur) - - def valide_val (self,valeur): - return self.object.valid_val(valeur) - - def info_erreur_item(self) : - commentaire="" - if self.definition.validators : - commentaire=self.definition.validators.info_erreur_item() - return commentaire - - def aide(self) : - commentaire="" - if self.definition.validators : - commentaire=self.definition.validators.aide() - return commentaire - - def info_erreur_liste(self) : - commentaire="" - if self.definition.validators : - commentaire=self.definition.validators.info_erreur_liste() - return commentaire - - def IsInIntervalle(self,valeur): - """ - Retourne 1 si la valeur est dans l'intervalle permis par - l'objet représenté par l'item. - """ - return self.valide_item(valeur) - - def isvalid(self): - valide=self.object.isvalid() - return valide - - #-------------------------------------------------- - # - # Autres ... - # - #--------------------------------------------------- - # SetText a priori inutilisee --> commentee - # GetIconName - # GetText - # getval a priori inutilisee --> commentee - # set_valeur_co - # get_sd_avant_du_bon_type - # verif a priori inutilisee --> commentee - # delete_valeur_co - - #def SetText(self, text): - # try: - # value = eval(text) - # self.object.setval(value) - # except: - # pass - - def GetIconName(self): - if self.isvalid(): - return "ast-green-ball" - elif self.object.isoblig(): - return "ast-red-ball" - else: - return "ast-yel-ball" - - def GetText(self): - """ - Classe SIMPTreeItem - Retourne le texte à afficher dans l'arbre représentant la valeur de l'objet - pointé par self - """ - text= self.object.GetText() - return text - - #def getval(self): - # return self.object.getval() - - def set_valeur_co(self,nom_co): - """ - Affecte au MCS pointé par self l'objet de type CO et de nom nom_co - """ - ret = self.object.set_valeur_co(nom_co) - #print "set_valeur_co",ret - return ret - - def get_sd_avant_du_bon_type(self): - """ - Retourne la liste des noms des SD présentes avant l'étape qui contient - le MCS pointé par self et du type requis par ce MCS - """ - a=self.object.etape.parent.get_sd_avant_du_bon_type(self.object.etape,self.object.definition.type) - return a - - def get_sd_avant_du_bon_type_pour_type_de_base(self): - a=self.object.jdc.get_sd_avant_du_bon_type_pour_type_de_base(self.object.etape,"LASSD") - return a - - - - #def verif(self): - # pass - - def delete_valeur_co(self,valeur=None): - """ - Supprime la valeur du mot cle (de type CO) - il faut propager la destruction aux autres etapes - """ - if not valeur : valeur=self.object.valeur - # XXX faut il vraiment appeler del_sdprod ??? - #self.object.etape.parent.del_sdprod(valeur) - self.object.etape.parent.delete_concept(valeur) - - #----------------------------------------------- - # - # Methodes liees au type de l objet attendu - # - #----------------------------------------------- - # wait_co - # wait_geom - # wait_complex - # wait_reel - # wait_shell - # wait_assd - # GetType - - def wait_co(self): - """ - Méthode booléenne qui retourne 1 si l'objet pointé par self - attend un objet de type ASSD qui n'existe pas encore (type CO()), - 0 sinon - """ - return self.object.wait_co() - - def wait_geom(self): - """ - Méthode booléenne qui retourne 1 si l'objet pointé par self - attend un objet GEOM, 0 sinon - """ - return self.object.wait_geom() - - def wait_complex(self): - """ Méthode booléenne qui retourne 1 si l'objet pointé par self - attend un complexe, 0 sinon """ - if 'C' in self.object.definition.type: - return 1 - else: - return 0 - - def wait_reel(self): - """ Méthode booléenne qui retourne 1 si l'objet pointé par self - attend un réel, 0 sinon """ - if 'R' in self.object.definition.type: - return 1 - else: - return 0 - - def wait_shell(self): - """ Méthode booléenne qui retourne 1 si l'objet pointé par self - attend un shell, 0 sinon """ - if 'shell' in self.object.definition.type: - return 1 - else: - return 0 - - def wait_assd(self): - """Méthode booléenne qui retourne 1 si l'objet pointé par self - attend un objet de type ASSD ou dérivé, 0 sinon """ - return self.object.wait_assd() - - def wait_assd_or_type_base(self) : - boo=0 - if len(self.object.definition.type) > 1 : - if self.wait_reel() : - boo = 1 - if 'I' in self.object.definition.type : - boo = 1 - return boo - - - def GetType(self): - """ - Retourne le type de valeur attendu par l'objet représenté par l'item. - """ - return self.object.get_type() - - #----------------------------------------------------- - # - # Methodes liees a l evaluation de la valeur saisie - # - #----------------------------------------------------- - # eval_valeur - # eval_valeur_item - # is_CO - # traite_reel - - def eval_valeur(self,valeur): - """ Lance l'interprétation de 'valeur' (chaîne de caractères) comme valeur de self : - - retourne l'objet associé si on a pu interpréter (entier, réel, ASSD,...) - - retourne 'valeur' (chaîne de caractères) sinon - """ - newvaleur=self.eval_val(valeur) - return newvaleur,1 - - def eval_valeur_BAK(self,valeur): - """ Lance l'interprétation de 'valeur' (chaîne de caractères) comme valeur - de l'objet pointé par self : - - retourne l'objet associé si on a pu interpréter (entier, réel, ASSD,...) - - retourne 'valeur' (chaîne de caractères) sinon - - retourne None en cas d invalidite - - retourne invalide si 1 des objets du tuple l est - """ - validite=1 - if type(valeur) in (types.ListType,types.TupleType) : - valeurretour=[] - for item in valeur : - newvaleur,validiteitem=self.eval_valeur_item(item) - valeurretour.append(newvaleur) - if validiteitem == 0: - validite=0 - else : - valeurretour,validite= self.eval_valeur_item(valeur) - if validite == 0 : - valeurretour = None - return valeurretour,validite - - def eval_valeur_item(self,valeur): - """ Lance l'interprétation de 'valeur' qui doit ne pas etre un tuple - - va retourner la valeur de retour et la validite - selon le type de l objet attendu - - traite les reels et les parametres - """ - #print "eval_valeur_item",valeur - if valeur==None or valeur == "" : - return None,0 - validite=1 - if self.wait_reel(): - valeurinter = self.traite_reel(valeur) - if valeurinter != None : - valeurretour,validite= self.object.eval_valeur(valeurinter) - else: - valeurretour,validite= self.object.eval_valeur(valeur) - elif self.wait_geom(): - valeurretour,validite = valeur,1 - else : - valeurretour,validite= self.object.eval_valeur(valeur) - #print "eval_valeur_item",valeurretour,validite - - if validite == 0: - if type(valeur) == types.StringType and self.object.wait_TXM(): - essai_valeur="'" + valeur + "'" - valeurretour,validite= self.object.eval_valeur(essai_valeur) - - if hasattr(valeurretour,'__class__'): - #if valeurretour.__class__.__name__ in ('PARAMETRE','PARAMETRE_EVAL'): - if valeurretour.__class__.__name__ in ('PARAMETRE',): - validite=1 - - #if self.wait_co(): - # CCAR : il ne faut pas essayer de creer un concept - # il faut simplement en chercher un existant ce qui a du etre fait par self.object.eval_valeur(valeur) - #try: - #valeurretour=Accas.CO(valeur) - #except: - #valeurretour=None - #validite=0 - # on est dans le cas où on a évalué et où on n'aurait pas du - if self.object.wait_TXM() : - if type(valeurretour) != types.StringType: - valeurretour=str(valeur) - validite=1 - return valeurretour,validite - - def is_CO(self,valeur=None): - """ - Indique si valeur est un concept produit de la macro - Cette méthode n'a de sens que pour un MCSIMP d'une MACRO - Si valeur vaut None on teste la valeur du mot cle - """ - # Pour savoir si un concept est un nouveau concept de macro - # on regarde s'il est présent dans l'attribut sdprods de l'étape - # ou si son nom de classe est CO. - # Il faut faire les 2 tests car une macro non valide peut etre - # dans un etat pas tres catholique avec des CO pas encore types - # et donc pas dans sdprods (resultat d'une exception dans type_sdprod) - if not valeur:valeur=self.object.valeur - if valeur in self.object.etape.sdprods:return 1 - if type(valeur) is not types.InstanceType:return 0 - if valeur.__class__.__name__ == 'CO':return 1 - return 0 - - def is_param(self,valeur) : - for param in self.jdc.params: - if (repr(param) == valeur): - return 1 - return 0 - - def traite_reel(self,valeur): - """ - Cette fonction a pour but de rajouter le '.' en fin de chaîne pour un réel - ou de détecter si on fait référence à un concept produit par DEFI_VALEUR - ou un EVAL ... - """ - valeur = string.strip(valeur) - liste_reels = self.get_sd_avant_du_bon_type() - if valeur in liste_reels: - return valeur - if len(valeur) >= 3 : - if valeur[0:4] == 'EVAL' : - # on a trouvé un EVAL --> on retourne directement la valeur - return valeur - if string.find(valeur,'.') == -1 : - # aucun '.' n'a été trouvé dans valeur --> on en rajoute un à la fin - if (self.is_param(valeur)): - return valeur - else: - if string.find(valeur,'e') != -1: - # Notation scientifique ? - try : - r=eval(valeur) - return valeur - except : - return None - else : - return valeur+'.' - else: - return valeur - - -import Accas -treeitem = SIMPTreeItem -objet = Accas.MCSIMP - diff --git a/InterfaceTK/definition_cata.py b/InterfaceTK/definition_cata.py deleted file mode 100644 index 156ea489..00000000 --- a/InterfaceTK/definition_cata.py +++ /dev/null @@ -1,462 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -# Modules Python -import types - -# Modules Eficas -import Accas -from Noyau.N_CR import CR - -class CATALOGUE: - def __init__(self,modules_cata): - self.modules_cata = modules_cata # tuple de modules... - self.cr = CR() - self.state='undetermined' - self.entites_attributs = {} - self.entites_fils = [] - self.build_entites_attributs() - self.build_entites_fils() - - def build_entites_attributs(self): - pass - - def build_entites_fils(self): - niv_types = Accas.NIVEAU(nom="types",label="Liste des types") - niv_commandes = Accas.NIVEAU(nom="commandes",label="Liste des commandes") - self.entites_fils.append(make_commande_cata(niv_types,self)) - self.entites_fils.append(make_commande_cata(niv_commandes,self)) - for module_cata in self.modules_cata: - for e in dir(module_cata): - obj = getattr(module_cata,e) - if isCMD(obj): - self.entites_fils[1].register(make_commande_cata(obj,self.entites_fils[1])) - elif type(obj) == types.ClassType: - if issubclass(obj,Accas.ASSD): - self.entites_fils[0].register(TYPE_CATA(obj)) - - def init_modif(self): - self.state = 'modified' - - def report(self): - """ Classe CATALOGUE - Methode pour generation d un rapport de validite - """ - self.cr.purge() - self.cr.debut="DEBUT CR validation : " - self.cr.fin="FIN CR validation :" - self.state = 'modified' - self.isvalid(cr='oui') - for fils in self.entites_fils[1].entites : - self.cr.add(fils.report()) - return self.cr - - def isvalid(self,cr='non'): - if self.state != 'unchanged': - valid=1 - for fils in self.entites_fils[1].entites_fils: - if not fils.isvalid(): - valid=0 - break - self.valid = valid - self.state='unchanged' - return self.valid - -def make_commande_cata(objet,pere): - if isinstance(objet,Accas.OPER): - return OPER_CATA(objet,pere,objet.nom) - elif isinstance(objet,Accas.PROC): - return PROC_CATA(objet,pere,objet.nom) - elif isinstance(objet,Accas.MACRO): - return MACRO_CATA(objet,pere,objet.nom) - elif isinstance(objet,Accas.FORM): - return MACRO_CATA(objet,pere,objet.nom) - elif isinstance(objet,Accas.NIVEAU): - return NIVEAU_CATA(objet,pere,objet.nom) - else: - print "Erreur dans make_commande_cata : on cherche à évaluer un objet non référencé ",objet - -def make_mc_cata(objet,pere,nom=''): - if isinstance(objet,Accas.BLOC): - return BLOC_CATA(objet,pere,nom) - elif isinstance(objet,Accas.FACT): - return FACT_CATA(objet,pere,nom) - elif isinstance(objet,Accas.SIMP): - return SIMP_CATA(objet,pere,nom) - else: - print "Erreur dans make_mc_cata : on cherche à évaluer un objet non référencé ",objet - -class TYPE_CATA: - def __init__(self,objet): - self.objet = objet - self.nom = objet.__name__ - - def isvalid(self,cr='non'): - return 1 - - def get_valeur_attribut(self,nom_attr): - if nom_attr == 'nom':return self.nom - return None - -class OBJET_CATA: - attributs=[] - attributs_defauts={} - def __init__(self,objet,pere,nom): - self.objet = objet - self.nom = nom - self.pere = pere - self.cr = CR() - self.state='undetermined' - self.entites_fils = [] - self.entites_attributs = {} - self.build_entites_attributs() - self.build_entites_fils() - - def __str__(self): - s='' - s=self.__class__.__name__+' : '+self.nom - return s - - def build_entites_attributs(self): - for attribut in self.attributs: - if hasattr(self.objet,attribut): - self.entites_attributs[attribut]=ATTR_CATA(attribut,getattr(self.objet,attribut)) - else: - if self.attributs_defauts.has_key(attribut): - self.entites_attributs[attribut]=ATTR_CATA(attribut,self.attributs_defauts[attribut]) - else: - self.entites_attributs[attribut]=ATTR_CATA(attribut,None) - - def build_entites_fils(self): - for k,v in self.objet.entites.items(): - self.entites_fils.append(make_mc_cata(v,self,nom=k)) - - def get_valeur_attribut(self,nom_attr): - if nom_attr in self.entites_attributs.keys(): - return self.entites_attributs[nom_attr].valeur - elif nom_attr in self.attributs_defauts.keys(): - return self.attributs_defauts[nom_attr] - elif nom_attr == 'domaine_validité': - if self.entites_attributs['into'].valeur != None : - return 'discret' - else: - return 'continu' - - def isvalid(self,cr='non'): - if self.state =='unchanged': - return self.valid - else: - valid = 1 - if hasattr(self,'valid'): - old_valid = self.valid - else: - old_valid = None - # on teste self lui-meme - if self.nom == '' or self.nom == None : valid=0 - # on teste les attributs - for attribut in self.entites_attributs.values(): - if not attribut.isvalid() : valid =0 - break - # on teste les fils - for fils in self.entites_fils: - if not fils.isvalid(): valid = 0 - break - self.valid = valid - self.state = 'unchanged' - if old_valid: - if old_valid != self.valid : self.init_modif_up() - return self.valid - - def init_modif_up(self): - self.pere.state='modified' - - def report(self): - self.cr.purge() - self.cr.debut="Debut "+self.__class__.__name__+' : '+self.nom - self.cr.fin = "Fin "+self.__class__.__name__+' : '+self.nom - self.isvalid(cr='oui') - for attribut in self.entites_attributs.values(): - self.cr.add(attribut.report()) - for fils in self.entites_fils : - self.cr.add(fils.report()) - return self.cr - - def set_valeur_attribut(self,nom_attr,valeur): - """ - Affecte la valeur 'valeur' à l'attribut de nom 'nom-attr' - """ - # il faudra être prudent sur les changements de nom : interdire de changer - # le nom d'un mot-clé qui serait utilisé dans une règle ??? - self.entites_attributs[nom_attr].valeur = valeur - - def addentite(self,name,pos): - """ - Permet d'ajouter un nouveau fils a self - """ - self.init_modif() - if name == 'new_simp': - objet = Accas.SIMP(typ=('bidon',)) - objet_cata = make_mc_cata(objet,self) - self.entites_fils.insert(pos,objet_cata) - return objet_cata - - def init_modif(self): - self.state = 'modified' - if hasattr(self,'pere'): - self.pere.init_modif() - - def verif_nom(self,cr='non'): - """ - Méthode appelée par EFICAS et ACCAS - Booléenne : retourne 1 si l'attribut nom est valide, 0 sinon - """ - if self.entites_attributs['nom'].valeur == '': - if cr == 'oui' : self.cr.fatal("L'objet de type %s n'est pas nommé" %self.__class__.__name__) - return 0 - return 1 - - def verif_defaut(self,cr='non'): - """ - Méthode de vérification de validité du défaut - """ - defaut = self.get_valeur_attribut('defaut') - if self.get_valeur_attribut('domaine_validite') == 'discret' : - if defaut not in self.get_valeur_attribut('into'): - if cr == 'oui' : self.cr.fatal("La valeur %s n'est pas autorisée" %str(defaut)) - return 0 - return 1 - else: - if defaut == None : return 1 - typ = self.get_valeur_attribut('type') - # on attend un TXM ? - if 'TXM' in typ : - if type(defaut) == types.StringType : return 1 - val_min = self.get_valeur_attribut('val_min') - val_max = self.get_valeur_attribut('val_max') - # on attend un reel ? - if 'R' in typ : - if type(defaut) == types.StringType: - try : - nb = string.atof(defaut) - except: - nb=None - else: - nb = defaut - if nb != None : - test = 1 - if val_min != '**' : test = (nb >= val_min) - if val_max != '**' : test = test*(nb <= val_max) - if test : return 1 - # on attend un entier ? - if 'I' in typ : - if type(defaut)==types.StringType: - try: - nb = string.atoi(defaut) - except: - pass - else: - nb = defaut - if nb != None : - test = 1 - if val_min != '**' : test = (nb >= val_min) - if val_max != '**' : test = test*(nb <= val_max) - if test : return 1 - # si on passe par là, c'est que l'on n'a pas su évaluer defaut - if cr == 'oui' : self.cr.fatal("La valeur %s n'est pas une valeur permise" %str(defaut)) - return 0 - - def verif_val_min(self,cr='non'): - """ - Méthode de vérification de val_min. - Booléenne : retourne 1 si val_min est valide, 0 sinon - """ - val_min = self.get_valeur_attribut('val_min') - if not val_min : - if cr == 'oui' : self.cr.fatal('val_min ne peut valoir None') - return 0 - if val_min == '**': return 1 - # val_min doit à ce stade être : - # - soit un entier ou un réel - # - soit une chaîne de caractères représentant un entier ou un réel (provient d'EFICAS) - if type(val_min) == types.StringType : - try : - val_min = string.atoi(val_min) - except: - try: - val_min = string.atof(val_min) - except: - if cr == 'oui' : self.cr.fatal("%s n'est ni un entier ni un réel" %str(val_min)) - return 0 - # A ce stade, val_min doit être un entier ou un réel : on vérifie ... - if type(val_min) not in (types.IntType,types.FloatType) : - if cr == 'oui' : self.cr.fatal("%s n'est pas d'un type autorisé" %str(val_min)) - return 0 - # A ce stade valeur est un entier ou un réel : on peut comparer à val_max - val_max = self.get_valeur_attribut('val_max') - if val_max == '**' or val_min < val_max : return 1 - # erreur : val_min est supérieur à val_max !!! - if cr == 'oui' : self.cr.fatal("%s n'est pas inférieur à %s" %(str(val_min),str(val_max))) - return 0 - - def verif_val_max(self,cr='non'): - """ - Méthode de vérification de val_max. - Booléenne : retourne 1 si val_max est valide, 0 sinon - """ - val_max = self.get_valeur_attribut('val_max') - if not val_max : - if cr == 'oui' : self.cr.fatal('val_max ne peut valoir None') - return 0 - if val_max == '**': return 1 - # val_max doit à ce stade être : - # - soit un entier ou un réel - # - soit une chaîne de caractères représentant un entier ou un réel (provient d'EFICAS) - if type(val_max) == types.StringType : - try : - val_max = string.atoi(val_max) - except: - try: - val_max = string.atof(val_max) - except: - if cr == 'oui' : self.cr.fatal("%s n'est ni un entier ni un réel" %str(val_max)) - return 0 - # A ce stade, val_max doit être un entier ou un réel : on vérifie ... - if type(val_max) not in (types.IntType,types.FloatType) : - if cr == 'oui' : self.cr.fatal("%s n'est pas d'un type autorisé" %str(val_max)) - return 0 - # A ce stade valeur est un entier ou un réel : on peut comparer à val_max - val_min = self.get_valeur_attribut('val_min') - if val_min == '**' or val_min < val_max : return 1 - # erreur : val_min est supérieur à val_max !!! - if cr == 'oui' : self.cr.fatal("%s n'est pas supérieur à %s" %(str(val_max),str(val_min))) - return 0 - -class OPER_CATA(OBJET_CATA): - attributs = ['ang','docu','fr','niveau','nom','op','op_init','reentrant','regles','repetable','sd_prod'] - -class PROC_CATA(OBJET_CATA): - attributs = ['ang','docu','fr','niveau','nom','op','op_init','regles','repetable'] - -class MACRO_CATA(OBJET_CATA): - attributs = ['ang','docu','fr','niveau','nom','op','op_init','reentrant','regles','repetable','sd_prod'] - -class BLOC_CATA(OBJET_CATA): - attributs = ['ang','condition','docu','fr','nom','regles'] - -class FACT_CATA(OBJET_CATA): - attributs=['ang','defaut','docu','fr','max','min','nom','regles','statut'] - -class SIMP_CATA(OBJET_CATA): - attributs=['ang','defaut','docu','fr','homo','into','max','min','nom','position','statut','type','val_min','val_max'] - attributs_defauts={'ang':'','defaut':None,'fr':'','homo':1,'into':None,'max':1,'min':1,'nom' : '','position':'local', - 'regles':None,'statut':'f','type':None,'val_min':'**','val_max':'**','docu':''} - - def build_entites_fils(self): - pass - - def isvalid(self,cr='non'): - """ - Mde appelpar l'externe (EFICAS et ACCAS). - Boolne : retourne 1 si l'objet est valide, 0 sinon - """ - if self.state == 'unchanged': - return self.valid - else: - valid = 1 - valid = valid*self.verif_nom(cr=cr) - valid = valid*self.verif_defaut(cr=cr) - valid = valid*self.verif_val_min(cr=cr)*self.verif_val_max(cr=cr) - if hasattr(self,'valid'): - old_valid = self.valid - else: - old_valid = None - self.valid = valid - self.state='unchanged' - if old_valid : - if old_valid != self.valid : self.init_modif_up() - return self.valid - -class NIVEAU_CATA(OBJET_CATA): - def __init__(self,objet,pere,nom): - self.pere = pere - self.nom = nom - self.state = 'undetermined' - self.cr = CR() - self.objet = objet - self.entites_fils=[] - self.entites_attributs = {} - - def register(self,fils): - """ - Enregistre la commande 굡pe : - - si editmode = 0 : on est en mode relecture d'un fichier de commandes - auquel cas on ajoute etape ࡬a fin de la liste self.etapes - - si editmode = 1 : on est en mode ajout d'굡pe depuis eficas auquel cas - cette mode ne fait rien, c'est addentité enregistre etape ࡬a bonne place - dans self.etapes - """ - self.entites_fils.append(fils) - - def unregister(self,etape): - self.entites_fils.remove(etape) - - def isvalid(self,cr='non'): - """ Mode boolne qui retourne 0 si le niveau est invalide, 1 sinon """ - if self.state == 'unchanged': - return self.valid - else: - valid = 1 - if len(self.entites_fils) == 0: - #valid = self.Accas.valide_vide - valid = 1 - else: - for commande in self.entites_fils : - if hasattr(commande,'isvalid'): - if not commande.isvalid() : - valid = 0 - break - else: - print str(commande)," n'a pas de methode isvalid" - if hasattr(self,'valid'): - old_valid = self.valid - else: - old_valid = None - self.valid = valid - self.state='unchanged' - if old_valid: - if old_valid != self.valid : self.init_modif_up() - return self.valid - - -class ATTR_CATA(OBJET_CATA): - def __init__(self,nom,valeur=None): - self.nom = nom - self.valeur = valeur - self.cr = CR() - self.state='undetermined' - self.entites_attributs={} - self.entites_fils=() - - def isvalid(self,cr='non'): - return 1 - -def isCMD(cmd): - return isinstance(cmd,Accas.OPER) or isinstance(cmd,Accas.PROC) or isinstance(cmd,Accas.MACRO) or isinstance(cmd,Accas.FORM) - diff --git a/InterfaceTK/eficas.py b/InterfaceTK/eficas.py deleted file mode 100644 index caf47fb8..00000000 --- a/InterfaceTK/eficas.py +++ /dev/null @@ -1,143 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -""" - Ce module contient la classe EFICAS qui est l'application - proprement dite. Elle est dérivée de la classe APPLI -""" -# Modules Python -import string -from Tkinter import Label -import Pmw -import traceback - -# Modules Eficas -from widgets import showerror -from widgets import askopenfilename -import patches -import appli -from widgets import Fenetre - -class EFICAS(appli.APPLI): - - try: - from prefs import appli_composants - except: - appli_composants=['readercata','bureau','browser','options'] - - def get_texte_infos(self): - texte=appli.APPLI.get_texte_infos(self) - texte = texte + 'Catalogue utilisé : %s\n' % self.bureau.fic_cata - return texte - - def exitEFICAS(self): - self.bureau.exitEFICAS() - - def getBureau(self): - return self.bureau - - def browse(self,result): - if result == 'Browse': - self.ulfile = askopenfilename(parent=self.dialog.component('hull'),title="Choix fichier :") - self._ulfile.setentry(self.ulfile) - elif result == 'OK': - self.ulfile = self._ulfile.get() - # On utilise le convertisseur défini par format_fichier - source=self.get_source(self.ulfile) - if source: - # On a réussi à convertir le fichier self.ulfile - self.dialog.deactivate(result) - self.text=source - else: - # Une erreur a été rencontrée - self.text='' - elif result == 'Cancel': - self._ulfile.setentry('') - self.dialog.deactivate(result) - self.ulfile = None - self.text="" - - def get_file(self,unite=None,fic_origine = ''): - """ - Retourne le nom du fichier correspondant a l unite logique unite (entier) - """ - if unite : - titre = "Choix unite %d " %unite - else: - titre = "Choix d'un fichier de poursuite" - self.dialog=Pmw.Dialog(self.top, - title = titre, - buttons = ('OK', 'Browse','Cancel'), - defaultbutton='OK', - command=self.browse, - ) - self.dialog.withdraw() - if unite : - texte = "Le fichier %s contient une commande INCLUDE \n" % fic_origine - texte = texte+'Donnez le nom du fichier correspondant\n à l unité logique %d' % unite - else: - texte="Le fichier %s contient une commande %s\n" %(fic_origine,'POURSUITE') - texte = texte+'Donnez le nom du fichier dont vous \n voulez faire une poursuite' - if self.test == 1: raise Exception("Erreur: "+texte) - w = Label(self.dialog.interior(), - text = texte) - w.pack(padx = 10, pady = 10) - if unite != None : - labeltexte = 'Fichier pour unite %d :' % unite - else: - labeltexte = 'Fichier à poursuivre :' - self._ulfile=Pmw.EntryField(self.dialog.interior(), - labelpos = 'w', - label_text = labeltexte, - ) - self._ulfile.pack(fill='x', expand=1, padx=10, pady=5) - self._ulfile.component('entry').focus_set() - self.dialog.activate(geometry='centerscreenalways') - return self.ulfile,self.text - - def get_source(self,file): - import convert - format=self.format_fichier.get() - # Il faut convertir le contenu du fichier en fonction du format - if convert.plugins.has_key(format): - # Le convertisseur existe on l'utilise - p=convert.plugins[format]() - p.readfile(file) - text=p.convert('execnoparseur') - if not p.cr.estvide(): - self.affiche_infos("Erreur à la conversion") - Fenetre(self, - titre="compte-rendu d'erreurs, EFICAS ne sait pas convertir ce fichier", - texte = str(p.cr)).wait() - return text - return text - else: - # Il n'existe pas c'est une erreur - self.affiche_infos("Type de fichier non reconnu") - showerror("Type de fichier non reconnu","EFICAS ne sait pas ouvrir ce type de fichier") - return None - - def affiche_texte(self,entete,texte): - """Cette methode ouvre une fenetre modale dans laquelle on affiche un texte - """ - self.affiche_infos(entete) - f=Fenetre(self, titre=entete, texte = texte) - f.wait() - diff --git a/InterfaceTK/eficas_go.py b/InterfaceTK/eficas_go.py deleted file mode 100644 index e6b00c5c..00000000 --- a/InterfaceTK/eficas_go.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -""" - Ce module permet de lancer l'application EFICAS en affichant - un ecran Splash pour faire patienter l'utilisateur -""" -# Modules Python -import sys -import Tkinter - -# Modules Eficas -import prefs -if hasattr(prefs,'encoding'): - # Hack pour changer le codage par defaut des strings - import sys - reload(sys) - sys.setdefaultencoding(prefs.encoding) - del sys.setdefaultencoding - # Fin hack - -import styles -from Editeur import import_code -import splash -from Editeur import session - -def lance_eficas(code=None,fichier=None): - """ - Lance l'appli EFICAS - """ - # Analyse des arguments de la ligne de commande - if code !=None : prefs.code=code - if code !=None : - sys.argv.append("-k") - sys.argv.append(code) - options=session.parse(sys.argv) - code=options.code - - root = Tkinter.Tk() - splash.init_splash(root,code=code,titre="Lancement d'EFICAS pour %s" %code) - splash._splash.configure(text="Chargement d'EFICAS en cours.\n Veuillez patienter ...") - import eficas - eficas.EFICAS(root,code=code,ihm="TK") - - root.mainloop() - diff --git a/InterfaceTK/eficas_test.py b/InterfaceTK/eficas_test.py deleted file mode 100644 index 2a5230cf..00000000 --- a/InterfaceTK/eficas_test.py +++ /dev/null @@ -1,105 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -""" - Ce module permet de lancer l'application EFICAS en affichant - un ecran Splash pour faire patentier l'utilisateur -""" -# Modules Python -import sys -import Tkinter - -# Modules Eficas -from Editeur import import_code -from Editeur import session - -def lance_eficas(code,fichier=None): - """ - Lance l'appli EFICAS - """ - options=session.parse(sys.argv) - root = Tkinter.Tk() - import eficas - if fichier : - a=eficas.EFICAS(root,code=code,fichier = fichier,test=1) - bureau=a.getBureau() - else: - eficas.EFICAS(root,code=code) - - print bureau.JDC.report() - bureau.closeJDC() - -def duplique_fichier(code,fichier=None,root=None): - print code - print fichier - if root == None : - root = Tkinter.Tk() - import eficas - import convert - import generator - import Editeur.utils - import string - - if fichier != None : - options=session.parse(sys.argv+[fichier]) - else : - options=session.parse(sys.argv) - - appli=eficas.EFICAS(root,code=code,fichier = fichier,test=1) - format='homard' - if convert.plugins.has_key(format): - p=convert.plugins[format]() - p.readfile(fichier) - text=p.convert('exec',appli) - print text - text2=convertir(text) - print text2 - cata=appli.readercata.cata - J=cata[0].JdC(procedure=text2,cata=cata) - J.analyse() - fileName=fichier+"_init" - if generator.plugins.has_key(format): - g=generator.plugins[format]() - jdc_formate=g.gener(J,format='beautifie') - jdc_fini = string.replace(jdc_formate,'\r\n','\n') - utils.save_in_file(fileName+".comm",jdc_fini,None) - -def convertir(texte): - import re - dict_change={"FICHIER_MED_MAILLAGE_N=":"FICHIER_MED_MAILLAGE_NP1","NOM_MED_MAILLAGE_N=":"NOM_MED_MAILLAGE_NP1"} - for mot in dict_change.keys(): - if( re.search(mot,texte)): - indicenouveau=re.search(mot,texte).end() - indicefinnouveau= texte.find(",",indicenouveau) - avant=dict_change[mot] - if( re.search(avant,texte)): - indiceancien=re.search(avant,texte).end()+1 - indicefinancien= texte.find(",",indiceancien) - valeur=texte[indiceancien:indicefinancien] - texte=texte[0:indicenouveau]+valeur+texte[indicefinnouveau:] - liste_mot_clef_None=['CRIT_RAFF_ABS','CRIT_RAFF_REL','CRIT_RAFF_PE','CRIT_DERA_ABS','CRIT_DERA_REL','CRIT_DERA_PE','NITER','NOM_MED_MAILLAGE_NP1','FICHIER_MED_MAILLAGE_NP1'] - - for mot in liste_mot_clef_None: - if( re.search(mot,texte)): - indice=re.search(mot,texte).end()+1 - indicefin= texte.find(",",indice) - texte=texte[0:indice]+"None"+texte[indicefin:] - return texte - diff --git a/InterfaceTK/faq.py b/InterfaceTK/faq.py deleted file mode 100644 index 30764b53..00000000 --- a/InterfaceTK/faq.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -""" - Ce module sert a afficher le texte du FAQ EFICAS - et à attendre l'acquittement par l'utilisateur -""" -# Modules Python -import os -import Pmw -from Tkinter import END - -# Modules Eficas -import prefs -import fontes - -class FAQ: - def __init__(self,parent): - self.parent=parent - self.Dialog = Pmw.Dialog(parent, - buttons=('Lu',), - title="FAQs et limitations d'EFICAS", - command = self.lu_FAQ) - txt = open(os.path.join(prefs.INSTALLDIR,'Editeur','faqs.txt'),'r').read() - Texte = Pmw.ScrolledText(self.Dialog.interior(), - text_font=fontes.standard) - Texte.insert(END,txt) - Texte.pack(expand=1,fill='both') - self.Dialog.activate(geometry = 'centerscreenalways') - - def lu_FAQ(self,event=None): - self.Dialog.destroy() - -def affiche(parent): - FAQ(parent) diff --git a/InterfaceTK/fenetre_mc_inconnus.py b/InterfaceTK/fenetre_mc_inconnus.py deleted file mode 100644 index 35b118ac..00000000 --- a/InterfaceTK/fenetre_mc_inconnus.py +++ /dev/null @@ -1,223 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -""" -""" -# Modules Python -from Tkinter import * -import copy - -# Modules Eficas -from centerwindow import centerwindow - -class fenetre_mc_inconnus : - """ - Cette classe sert à construire la fenêtre qui apparaît dans EFICAS - lorsque des mots-clés inconnus ont été trouvés dans le fichier de - commandes que l'on est en train de lire - """ - def __init__(self,l_mc): - self.l_mc = l_mc - self.fenetre = Toplevel() - self.fenetre.withdraw() - self.fenetre.geometry("400x400+0+0") - self.fenetre.title("Mots-clés inconnus dans le fichier de commandes") - self.init() - self.init_frames() - self.init_label() - self.init_liste_mc() - self.init_boutons() - centerwindow(self.fenetre) - self.fenetre.deiconify() - - def init(self) : - """ - Initialise les structures de données - """ - self.new_l_mc = [] - for mc in self.l_mc : - self.new_l_mc.append(copy.copy(mc)) - self.mc_courant = None - self.var_quit = IntVar(0) - self.entry_courante = None - - def init_frames(self): - """ - Création des 2 frames devant contenir le label et la liste des MC inconnus - """ - self.frame1 = Frame(self.fenetre) - self.frame2 = Frame(self.fenetre) - self.frame3 = Frame(self.fenetre) - self.frame1.place(relx=0,rely=0,relheight=0.2,relwidth=1) - self.frame2.place(relx=0,rely=0.2,relheight=0.6,relwidth=1) - self.frame3.place(relx=0,rely=0.8,relheight=0.2,relwidth=1) - - def init_label(self): - """ - Affichage du label dans la zone concernée - """ - txt = " Un ou plusieurs mots-clés inconnus ont été trouvés dans le fichier de commandes." - #txt = txt + "En cliquant sur leur nom, vous pourrez soit corriger l'orthographe soit supprimer ce mot-clé" - self.fenetre.update_idletasks() - Label(self.frame1, - text = txt, - wraplength = int(self.frame1.winfo_width()*0.8), - justify = 'center').place(relx=0.5,rely=0.5,anchor='center') - - - def init_liste_mc(self): - """ - Affiche les mots-clés à modifier ou supprimer - """ - i=0 - self.widgets=[] - for mc in self.l_mc : - # mc est une liste : - # mc contient comme premiers arguments l'étape et éventuellement les blocs, mcfact ... - # et contient comme 2 derniers éléments le nom du mot-clé et sa valeur - path_mc = self.get_path(mc[0:-2]) - nom_mc = mc[-2] - lab=Label(self.frame2,text = path_mc) - lab.grid(row=i,column=1,sticky=W) - e = Entry(self.frame2) - e.grid(row=i,column=0,sticky=W) - e.insert(END,nom_mc) - #e.bind("",lambda event,en=e,m=mc,s=self : s.select_mc(m,en)) - #e.bind("",lambda e,s=self : s.modifie_mc()) - e.configure(relief='flat',state='disabled') - self.widgets.append((e,lab)) - i=i+1 - - def init_boutons(self): - """ - Construit les boutons Modifier,Supprimer et Fermer - Les deux premiers sont inactifs tant qu'aucun mot-clé n'est sélectionné - """ - self.b_mod = Button(self.frame3, - text = "Modifier", - disabledforeground = 'grey35', - state='disabled', - command = self.modifie_mc) - self.b_sup = Button(self.frame3, - text = "Supprimer", - disabledforeground = 'grey35', - state='disabled', - command = self.supprime_mc) - self.b_quit = Button(self.frame3, - text = "Fermer", - command = self.quit) - #self.b_mod.place(relx=0.25,rely=0.5,anchor='center') - #self.b_sup.place(relx=0.50,rely=0.5,anchor='center') - #self.b_quit.place(relx=0.75,rely=0.5,anchor='center') - self.b_quit.place(relx=0.50,rely=0.5,anchor='center') - - def wait_new_list(self): - """ - Cette méthode rend cette toplevel bloquante. - Dès que la variable var_quit est modifiée, on continue l'exécution de cette - méthode (et on quitte) - """ - self.fenetre.wait_variable(self.var_quit) - self.fenetre.destroy() - return self.new_l_mc - - def get_path(self,l_o): - """ - Construit la chaîne de caractère contenant le chemin d'accès complet du mot-clé - """ - txt = '' - for o in l_o : - txt = txt + o.nom+'/' - # on enlève le dernier slash en trop - txt = txt[0:-1] - return txt - - def select_mc(self,mc,entry): - """ - Enregistre le mot-clé passé en argument comme mot-clé courant - Active les boutons Modifier et Supprimer - """ - self.desactive_entry() - self.mc_courant = mc - self.entry_courante = entry - self.active_boutons() - self.active_entry() - - def modifie_mc(self): - """ - Modifie le nom du mot-clé en prenant la nouvelle valeur lue dans entry_courante - """ - new_nom_mc = self.entry_courante.get() - index = self.l_mc.index(self.mc_courant) - new_mc = self.new_l_mc[index] - new_mc[-2] = new_nom_mc - objet_pere = self.mc_courant[-3] - - self.desactive_boutons() - self.desactive_entry() - - def supprime_mc(self): - """ - Supprime le mot-clé courant de la liste - """ - index = self.l_mc.index(self.mc_courant) - self.new_l_mc[index] = None - e,lab=self.widgets[index] - e.grid_remove() - lab.grid_remove() - self.desactive_boutons() - self.desactive_entry() - - def desactive_boutons(self): - """ - Désactive les boutons Modifier et Supprimer - """ - self.b_mod.configure(state='disabled') - self.b_sup.configure(state='disabled') - - def active_boutons(self): - """ - Active les boutons Modifier et Supprimer - """ - self.b_mod.configure(state='normal') - self.b_sup.configure(state='normal') - - def desactive_entry(self): - """ - Désactive l'entry courante si elle existe - """ - if self.entry_courante : - self.entry_courante.configure(state='disabled',relief='flat') - - def active_entry(self): - """ - Active l'entry courante si elle existe - """ - if self.entry_courante : - self.entry_courante.configure(state='normal',relief='sunken') - - def quit(self): - """ - Permet de fermer la fenêtre - """ - self.var_quit.set(1) - -if __name__ == '__main__': - fenetre_mc_inconnus(('toto','titi')) diff --git a/InterfaceTK/fonctionpanel.py b/InterfaceTK/fonctionpanel.py deleted file mode 100644 index b17704d5..00000000 --- a/InterfaceTK/fonctionpanel.py +++ /dev/null @@ -1,293 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -# Modules Python -import string,types,os -from Tkinter import * -import Pmw -from copy import copy,deepcopy -import traceback - -# Modules Eficas -from Editeur import Objecttreeitem -import prefs -import panels -import images -from widgets import ListeChoix -from widgets import FenetreDeSelection -from widgets import askopenfilename -from widgets import showinfo - -from Noyau.N_CR import justify_text -from Editeur.utils import substract_list -from plusieursbasepanel import PLUSIEURS_BASE_Panel - - -class FONCTION_Panel(PLUSIEURS_BASE_Panel): - def makeValeurPage(self,page): - """ - Crée la page de saisie d'une liste de valeurs à priori quelconques, - cad qui ne sont pas à choisir dans une liste prédéfinie - """ - genea=self.node.item.get_genealogie() - if "VALE" in genea: - self.nb_valeurs=2 - if "VALE_C" in genea: - self.nb_valeurs=3 - # On récupère la bulle d'aide du panneau, l'objet, l'aide,min et max (cardinalité de la liste), - # et la liste des valeurs déjà affectées à l'objet courant - bulle_aide=self.get_bulle_aide() - objet_mc = self.node.item.get_definition() - aide = self.get_aide() - aide = justify_text(texte=aide) - min,max = self.node.item.GetMinMax() - l_valeurs = self.node.item.GetListeValeurs() - l2_valeurs=self.decoupeListeValeurs(l_valeurs) - - # création des frames globales - self.frame1 = Frame(page,relief='groove',bd=2) - self.frame2 = Frame(page) - self.frame1.place(relx=0.,rely=0.,relwidth=1.,relheight=0.85) - self.frame2.place(relx=0.,rely=0.85,relwidth=1,relheight=0.15) - self.frame_right = Frame(self.frame1) - self.frame_right.place(relx=0.35,rely=0.,relwidth=0.65,relheight=1.) - - # création des frames internes - self.frame_valeurs = Frame(self.frame1) - self.frame_valeurs.place(relx=0.02,rely=0.05,relwidth=0.35,relheight=0.95) - self.frame_boutons_fleches = Frame(self.frame_right) - self.frame_boutons_fleches.place(relx=0.,rely=0.2,relwidth=0.2,relheight=0.5) - self.frame_choix = Frame(self.frame_right) - self.frame_choix.place(relx=0.2,rely=0.2,relwidth=0.7,relheight=0.5) - self.frame_aide = Frame(self.frame_right) - self.frame_aide.place(relx=0.1,rely=0.7,relwidth=0.8,relheight=0.3) - self.frame_boutons = Frame(self.frame2) - self.frame_boutons.place(relx=0.35,rely=0.,relwidth=0.5,relheight=1.) - for fram in (self.frame1,self.frame2,self.frame_right,self.frame_valeurs, - self.frame_boutons_fleches,self.frame_choix,self.frame_aide,self.frame_boutons): - fram.bind("",lambda e,s=self,a=bulle_aide : s.parent.appli.affiche_aide(e,a)) - fram.bind("",self.parent.appli.efface_aide) - - # création des objets dans les frames - liste_commandes_valeurs = (("",self.selectValeur), - ("",self.deselectValeur), - ("",self.afficheValeurListe)) - self.Liste_valeurs = ListeChoix(self,self.frame_valeurs,l2_valeurs,liste_commandes = liste_commandes_valeurs, - titre="Valeur(s) actuelle(s)") - - # Création de l'entry ou de la liste des SD - self.label = Label(self.frame_choix,text="Valeur :") - self.make_entry(frame = self.frame_choix,command = self.add_double_valeur_plusieurs_base) - self.label.place(relx=0.05,rely=0.5) - - # Création d'un bouton "Importer ..." sur le panel. - bouton_valeurs_fichier = Button(self.frame_choix, - text="Importer ...", - command=self.select_in_file) - bouton_valeurs_fichier.place(relx=0.28,rely=0.7,relwidth=0.6) - self.ajout_valeurs = None - - # boutons Ajouter et Supprimer - self.bouton_add = Button(self.frame_boutons_fleches, - image = images.get_image('arrow_left'), - command = self.add_double_valeur_plusieurs_base) - self.bouton_sup = Button(self.frame_boutons_fleches, - image = images.get_image('arrow_right'), - command = self.sup_valeur_sans_into) - self.bouton_add.place(relx=0.3,rely=0.35) - self.bouton_sup.place(relx=0.3,rely=0.65) - # affichage de l'aide - self.frame_aide.update() - self.aide = Label(self.frame_aide, - text = aide, - justify='center', - anchor='center', - wraplength=int(self.frame_aide.winfo_width()*0.8)) - self.aide.place(relx=0.5,rely=0.5,anchor='center',relwidth=1) - self.Liste_valeurs.affiche_liste() - # boutons Accepter et Annuler - self.bouton_accepter = Button(self.frame_boutons, - text='Valider', - command = lambda s=self,m=min,M=max : s.accepte_modifs_valeur_recolle(m,M)) - self.bouton_annuler = Button(self.frame_boutons, - text = 'Annuler', - command = self.annule_modifs_valeur) - for but in (self.bouton_accepter,self.bouton_annuler): - but.pack(side='left',padx=4) - - - def afficheValeurListe(self,name): - self.display_valeur(name) - - def decoupeListeValeurs(self,liste): - #decoupe la liste des valeurs en n ( les x puis les y) - nb=self.nb_valeurs - l_valeurs=[] - if (len(liste)%nb != 0): - message="La cardinalité n'est pas correcte, la dernière valeur est ignorée" - showinfo("Problème",message) - for i in range(len(liste)/nb) : - if (nb==2): - t=(liste[i*nb], liste[i*nb+1]) - else: - t=(liste[i*nb], liste[i*nb+1], liste[i*nb+2]) - l_valeurs.append(t) - return l_valeurs - - - def accepte_modifs_valeur_recolle(self,min,max): - l_valeurs=[] - l1_valeurs = self.Liste_valeurs.get_liste() - for val in l1_valeurs : - for item in val : - l_valeurs.append(item) - self.accepte_modifs_valeur(min,max,l_valeurs) - - - def add_double_valeur_plusieurs_base(self): - # on verifie qu'il s agit bien d un tuple - # on enleve les parentheses eventuelles - #doublevaleur_entree,validite,commentaire=self.get_valeur_double() - doublevaleur_entree= self.entry.get() - try: - if doublevaleur_entree[0]=='(' : - doublevaleur_entree=doublevaleur_entree[1:-1] - if doublevaleur_entree[-1]==')' : - doublevaleur_entree=doublevaleur_entree[0:-2] - val1=doublevaleur_entree.split(',')[0] - val2=doublevaleur_entree.split(',')[1] - saisie=(val1,val2) - if (self.nb_valeurs==3): - val3=doublevaleur_entree.split(',')[2] - saisie=(val1,val2,val3) - self.entry.delete(0,END) - except : - commentaire = "%s n est pas un tuple de la forme (x,y)" %`doublevaleur_entree` - if (self.nb_valeurs==3): - commentaire = "%s n est pas un tuple de la forme (x,y,z)" %`doublevaleur_entree` - self.parent.appli.affiche_infos(commentaire) - return - - # et seulement d un tuple - try: - val=doublevaleur_entree.split(',')[self.nb_valeurs] - commentaire = "%s n est pas un tuple de la forme (x,y)" %`doublevaleur_entree` - if (self.nb_valeurs==3): - commentaire = "%s n est pas un tuple de la forme (x,y,z)" %`doublevaleur_entree` - self.parent.appli.affiche_infos(commentaire) - self.parent.appli.affiche_infos(commentaire) - return - except : - # c est la le cas normal - pass - - # on verifie la validite des valeurs sont correctes - valeur,validite=self.node.item.eval_valeur(saisie) - if not validite : - commentaire = "impossible d'évaluer : %s " %`doublevaleur_entree` - self.parent.appli.affiche_infos(commentaire) - return - - # on verifie la validite de la liste - liste=[] - l1_valeurs = self.Liste_valeurs.get_liste() - for val in l1_valeurs : - for item in val : - liste.append(item) - validite_liste=self.node.item.valide_liste_partielle(valeur[0],liste) - if not validite_liste: - commentaire = "impossible d'ajouter %s a la liste " %`doublevaleur_entree` - self.parent.appli.affiche_infos(commentaire) - return - # liste a deja ete modifiee par l appel precedent a valide_liste_partielle - # et contient deja valeur[0] - validite_liste=self.node.item.valide_liste_partielle(valeur[1],liste) - if not validite_liste: - commentaire = "impossible d'ajouter %s a la liste " %`doublevaleur_entree` - self.parent.appli.affiche_infos(commentaire) - return - - # si une valeur est selectionnee on insere apres - # sinon on ajoute la valeur à la fin - if (self.Liste_valeurs.selection != None): - ligne=self.Liste_valeurs.cherche_selected_item() - if self.nb_valeurs==2: - l1_valeurs.insert(ligne,(valeur[0],valeur[1])) - else : - l1_valeurs.insert(ligne,(valeur[0],valeur[1],valeur[2])) - else : - if self.nb_valeurs==2: - l1_valeurs.append((valeur[0],valeur[1])) - else : - l1_valeurs.append((valeur[0],valeur[1],valeur[2])) - i = 0 - while i < self.nb_valeurs : - self.set_valeur_texte(saisie[i]) - i=i+1 - self.Liste_valeurs.put_liste(l1_valeurs) - self.Liste_valeurs.affiche_liste() - - - def display_valeur(self,val=None): - """ - Affiche la valeur passée en argument dans l'entry de saisie. - Par défaut affiche la valeur du mot-clé simple - Doit être redéfinie pour un pb avec les parametres dans un tuple - """ - if not val : - valeur = self.node.item.object.getval() - else: - valeur = val - if not valeur : return - - try: - affiche="(" - separe="" - for val in valeur: - affiche=affiche+separe+str(val) - separe="," - affiche=affiche+")" - self.entry.delete(0,END) - self.entry.insert(0,affiche) - except : - self.entry.delete(0,END) - -# Surcharge de select in file pour prendre en compte la saisie de tuple - def select_in_file(self): - """ Permet d'ouvrir un fichier choisi par l'utilisateur. """ - nom_fichier = askopenfilename(title="Choix fichier :") - - if not nom_fichier: - return - - try: - f = open(nom_fichier, "rb") - selection_texte = f.read() - f.close() - self.add_double_valeur_plusieurs_base = FenetreDeSelection(self, - self.node.item, - self.parent.appli, - titre="Sélection de valeurs", - texte=selection_texte, - cardinal = self.nb_valeurs) - except: - traceback.print_exc() - showinfo("Erreur de fichier","impossible d'ouvir le fichier "+nom_fichier) - diff --git a/InterfaceTK/fontes.py b/InterfaceTK/fontes.py deleted file mode 100644 index 8e158927..00000000 --- a/InterfaceTK/fontes.py +++ /dev/null @@ -1,36 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -standard = ("Times",10) -standard_italique = ("Times",10,'italic') -standard_gras = ("Times",10,'bold') -standard_gras_souligne = ("Times",10,'bold','underline') - -canvas = ('times',8) -canvas_italique = ('times',8,'italic') -canvas_gras = ("Times",8,'bold') -canvas_gras_italique = ("Times",10,'bold','italic') - -standard12 = ("Times",12) -standard12_gras = ("Times",12,'bold') -standard12_gras_italique = ( "times",12,'bold','italic') - -standardcourier10 = ("Courier",10) - diff --git a/InterfaceTK/images.py b/InterfaceTK/images.py deleted file mode 100644 index a6f0a74e..00000000 --- a/InterfaceTK/images.py +++ /dev/null @@ -1,67 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -""" - Ce module joue le role de cache pour les images stockées - dans le repertoire ICONDIR -""" - -import os -import Tkinter - -if __name__ == '__main__': - # Programme de test - import sys - import images - root=Tkinter.Tk() - frame = Tkinter.Frame(root) - frame.pack(expand=1,fill='both') - - for name in ('About24','Save24'): - Tkinter.Label(frame, image=images.get_image(name)).pack(side=Tkinter.TOP) - - root.mainloop() - sys.exit() - -try: - import prefs - ICONDIR=prefs.ICONDIR -except: - # Par defaut on utilise le repertoire local icons - ICONDIR=os.path.join(os.path.abspath(os.path.dirname(__file__)),'/Editeur/icons') - - -dico_images={} - -def get_image(name): - if dico_images.has_key(name): - return dico_images[name] - else : - fic_image = os.path.join(ICONDIR,name) - if not os.path.isfile(fic_image): - file, ext = os.path.splitext(fic_image) - fic_image = file + '.gif' - image = Tkinter.PhotoImage(file=fic_image) - dico_images[name]=image - return image - -def update_cache(): - dico_images.clear() - diff --git a/InterfaceTK/jdcdisplay.py b/InterfaceTK/jdcdisplay.py deleted file mode 100644 index fd0ac827..00000000 --- a/InterfaceTK/jdcdisplay.py +++ /dev/null @@ -1,285 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -""" - Ce module contient la classe JDCDISPLAY qui réalise l'affichage - du jeu de commandes sous la forme d'un arbre et de panneaux qui portent - les informations attachées au noeud de l'arbre sélectionné -""" -# Modules Python -import types,sys -import traceback -import Tkinter -import Pmw - -# Modules Eficas -import panels -from treeitemincanvas import TREEITEMINCANVAS -from widgets import showinfo,showerror - -class CONFIG: - isdeveloppeur='NON' - -class JDCDISPLAY: - """ - Cette classe ajoute à la class TREEITEMINCANVAS l'affichage des infos - attachées au noeud sélectionné dans un notebook - L'objet item associé au jdc est créé par la classe TREEITEMINCANVAS - """ - def __init__(self,jdc,nom_jdc,appli=None,parent=None): - self.jdc=jdc - self.nom_jdc=nom_jdc - self.fichier=None - self.panel_courant=None - - if not appli: - class Appli: - def __init__(self): - self.CONFIGURATION=CONFIG() - def affiche_infos(self,message): - print message - return - - def efface_aide(self,event): - return - - def affiche_aide(self,event,aide): - print aide - return - - appli=Appli() - self.appli=appli - - if not parent: - parent=Tkinter.Tk() - Pmw.initialise(parent) - self.parent=parent - self.node_selected = None - self.modified='n' - - self.pane=Pmw.PanedWidget(self.parent,orient='horizontal') - self.pane.add('treebrowser',min=0.4,size=0.5) - self.pane.add('selected',min=0.4) - self.pane.pack(expand=1,fill='both') - self.tree=TREEITEMINCANVAS(jdc,nom_jdc,self.pane.pane('treebrowser'), - self.appli,self.select_node,self.make_rmenu) - - def make_rmenu(self,node,event): - if hasattr(node.item,'rmenu_specs'): - rmenu = Tkinter.Menu(self.pane.pane('treebrowser'), tearoff=0) - #node.select() - self.cree_menu(rmenu,node.item.rmenu_specs,node) - rmenu.tk_popup(event.x_root,event.y_root) - - def cree_menu(self,menu,itemlist,node): - """ - Ajoute les items du tuple itemlist - dans le menu menu - """ - number_item=0 - radio=None - for item in itemlist: - number_item=number_item + 1 - if not item : - menu.add_separator() - else: - label,method=item - if type(method) == types.TupleType: - # On a un tuple => on cree une cascade - menu_cascade=Tkinter.Menu(menu) - menu.add_cascade(label=label,menu=menu_cascade) - self.cree_menu(menu_cascade,method,node) - elif method[0] == '&': - # On a une chaine avec & en tete => on cree un radiobouton - try: - command=getattr(node.item,method[1:]) - menu.add_radiobutton(label=label,command=lambda a=self.appli,c=command,n=node:c(a,n)) - if radio == None:radio=number_item - except:pass - else: - try: - command=getattr(node.item,method) - menu.add_command(label=label,command=lambda a=self.appli,c=command,n=node:c(a,n)) - except:pass - # Si au moins un radiobouton existe on invoke le premier - if radio:menu.invoke(radio) - - def select(self): - return - - def unselect(self): - return - - def select_node(self,node): - """ - Cette méthode est appelée à chaque fois qu'un noeud est sélectionné - dans l'arbre. - Elle permet l'affichage du panneau correspondant au noeud sélectionné - """ - if node is not self.node_selected : - #ATTENTION: il faut affecter l'attribut node_selected avant d'appeler - # create_panel pour eviter une recursion infinie entre create_panel, - # Emit, onValid, select_node - self.node_selected = node - self.create_panel(node) - elif self.panel_courant: - self.panel_courant.update_panel() - - def create_panel(self,node): - """ - Lance la génération du panneau contextuel de l'objet sélectionné - dans l'arbre - """ - if self.panel_courant: - # On detruit le panneau - self.panel_courant.destroy() - o=self.panel_courant - self.panel_courant=None - # Mettre à 1 pour verifier les cycles entre objets - # pour les panneaux - withCyclops=0 - if withCyclops: - from Misc import Cyclops - z = Cyclops.CycleFinder() - z.register(o) - del o - z.find_cycles() - z.show_stats() - z.show_cycles() - - if node is None: - self.panel_courant=None - return self.panel_courant - - if node.item.isactif(): - if hasattr(node.item,"panel"): - self.panel_courant=node.item.panel(self,self.pane.pane('selected'),node) - else: - raise Exception("Le noeud sélectionné n'a pas de panel associé") - else: - self.panel_courant = panels.Panel_Inactif(self,self.pane.pane('selected'),node) - return self.panel_courant - - def init_modif(self): - """ - Met l'attribut modified à 'o' : utilisé par Eficas pour savoir - si un JDC doit être sauvegardé avant destruction ou non - """ - self.modified = 'o' - - def stop_modif(self): - """ - Met l'attribut modified à 'n' : utilisé par Eficas pour savoir - si un JDC doit être sauvegardé avant destruction ou non - """ - self.modified = 'n' - - def mainloop(self): - self.parent.mainloop() - - def ReplaceObjectNode(self,node,new_object,nom_sd=None): - """ - Cette méthode sert à remplacer l'objet pointé par node par - new_object. - Si nom_sd : on remplace un OPER et on essaie de renommer la - nouvelle sd par nom_sd - """ - child = node.append_brother(new_object,retour='oui') - if child == 0: - self.appli.affiche_infos("Impossible de remplacer l'objet du noeud courant") - else: - self.init_modif() - node.delete() - #if nom_sd: - #child.item.nomme_sd(nom_sd) - child.select() - #child.update() - - def doCut(self): - """ - Stocke dans Eficas.noeud_a_editer le noeud à couper - """ - if not self.node_selected.item.iscopiable(): - showinfo("Copie impossible", - "Cette version d'EFICAS ne permet que la copie d'objets de type 'Commande' ou mot-clé facteur") - return - self.appli.edit="couper" - self.appli.noeud_a_editer = self.node_selected - - def doCopy(self): - """ - Stocke dans Eficas.noeud_a_editer le noeud à copier - """ - if not self.node_selected.item.iscopiable(): - showinfo("Copie impossible", - "La copie d'un tel objet n'est pas permise") - return - self.appli.edit="copier" - self.appli.noeud_a_editer = self.node_selected - - def doPaste(self): - """ - Lance la copie de l'objet placé dans self.appli.noeud_a_editer - Ne permet que la copie d'objets de type Commande ou MCF - """ - try: - child=self.appli.noeud_a_editer.doPaste(self.node_selected) - except: - #traceback.print_exc() - showinfo("Action de coller impossible", - "L'action de coller apres un tel objet n'est pas permise") - return - - if child == 0: - if self.appli.message != '': - showerror("Copie refusée",self.appli.message) - self.appli.message = '' - self.appli.affiche_infos("Copie refusée") - return - - # il faut déclarer le JDCDisplay_courant modifié - self.init_modif() - # suppression éventuelle du noeud sélectionné - # si possible on renomme l objet comme le noeud couper - if self.appli.edit == "couper": - #nom = self.appli.noeud_a_editer.item.object.sd.nom - item=self.appli.noeud_a_editer.item - self.appli.noeud_a_editer.delete() - child.item.update(item) - #test,mess = child.item.nomme_sd(nom) - child.select() - # on rend la copie à nouveau possible en libérant le flag edit - self.appli.edit="copier" - - def update(self): - """Cette methode est utilisee par le JDC associe pour - signaler des modifications globales du JDC - """ - self.tree.update() - - def supprime(self): - #print "supprime",self - self.select_node(None) - self.tree.supprime() - self.tree=None - self.pane.destroy() - - #def __del__(self): - # print "__del__",self diff --git a/InterfaceTK/listeFichiers.py b/InterfaceTK/listeFichiers.py deleted file mode 100644 index 908bfe2b..00000000 --- a/InterfaceTK/listeFichiers.py +++ /dev/null @@ -1,81 +0,0 @@ -import string - -class listeFichiers : - - def __init__(self,appli): - self.appli=appli - self.premiere=1 - self.nbfich=0 - self.rep=self.appli.CONFIGURATION.rep_user - self.menuFichier=self.appli.menubar.menudict['Fichier'] - self.monFichier=self.rep+"/listefichiers_"+self.appli.code - self.liste_Fichiers=[] - self.init_Fichier() - self.traite_liste() - - def init_Fichier(self): - index=0 - try : - f=open(self.monFichier) - while ( index < 5) : - ligne=f.readline() - if ligne != "" : - l=(ligne.split("\n"))[0] - self.liste_Fichiers.append(l) - index=index+1 - except : - pass - try : - f.close() - except : - pass - - def sauve_Fichier(self): - try : - if len(self.liste_Fichiers) == 0 : - return - f=open(self.monFichier,'w') - index=0 - while ( index < len(self.liste_Fichiers)): - ligne=self.liste_Fichiers[index]+"\n" - f.write(ligne) - index=index+1 - except : - pass - try : - f.close() - except : - pass - - def traite_liste(self): - index=0 - for index in range(self.nbfich): - self.menuFichier.delete(9) - self.nbfich = 0 - index = 0 - while( index < len(self.liste_Fichiers)) : - self.ajout_item(index) - index=index+1 - - def ajout_item(self,index): - if self.premiere and (len(self.liste_Fichiers)!=0): - self.premiere=0 - self.menuFichier.add_separator() - label=self.liste_Fichiers[index] - self.menuFichier.insert_command(8,label=label,command= lambda self=self, l=label:self.coucou (l)); - self.nbfich=self.nbfich+1 - - def coucou(self,label): - self.appli.bureau.openJDC(file=label) - - def aOuvert(self,file): - if file not in self.liste_Fichiers : - if (len(self.liste_Fichiers) > 4) : - f=self.liste_Fichiers[0] - self.liste_Fichiers.remove(f) - self.liste_Fichiers.insert(len(self.liste_Fichiers),file) - else: - self.liste_Fichiers.remove(file) - self.liste_Fichiers.insert(len(self.liste_Fichiers),file) - self.traite_liste() - self.sauve_Fichier() diff --git a/InterfaceTK/listePatronsTK.py b/InterfaceTK/listePatronsTK.py deleted file mode 100644 index 350749b1..00000000 --- a/InterfaceTK/listePatronsTK.py +++ /dev/null @@ -1,27 +0,0 @@ -import os -import re -import Tkinter - - -from Editeur import listePatrons - -class listePatronsTK(listePatrons.listePatrons) : - - def __init__(self,appli): - self.appli=appli - listePatrons.listePatrons.__init__(self) - self.ajout_menu() - - def ajout_menu(self): - menuFichier=self.appli.menubar.menubar - menu_cascade=Tkinter.Menu(menuFichier,tearoff=0) - menuFichier.add_cascade(label="Patrons",menu=menu_cascade) - for ss_menu in self.liste.keys(): - ssmenu=Tkinter.Menu(menu_cascade,tearoff=0) - menu_cascade.add_cascade(label=ss_menu,menu=ssmenu) - for fichier in self.liste[ss_menu]: - ssmenu.add_command(label=fichier,command= lambda self=self, l=fichier:self.ouvre(l)); - - def ouvre(self,label): - fichier=self.rep_patrons+"/"+label - self.appli.bureau.openJDC(file=fichier,enregistre="non") diff --git a/InterfaceTK/macrodisplay.py b/InterfaceTK/macrodisplay.py deleted file mode 100644 index a0e7e8de..00000000 --- a/InterfaceTK/macrodisplay.py +++ /dev/null @@ -1,165 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -""" - Ce module contient la classe MacroDisplay qui realise l'affichage - des sous commandes d'une macro sous forme d'arbre -""" -# Modules Python -import types,sys -import Tkinter,Pmw - -# Modules EFICAS -import images -import tooltip -from Editeur import Objecttreeitem -import compojdc -import treewidget -from widgets import Fenetre -from Ihm import CONNECTOR - -class MACRO2TreeItem(compojdc.JDCTreeItem): - pass - -class MacroDisplay: - def __init__(self,appli,macroitem,nom_jdc): - self.fenetre = Tkinter.Toplevel() - self.fenetre.configure(width = 800,height=500) - self.fenetre.protocol("WM_DELETE_WINDOW", self.quit) - self.fenetre.title("Visualisation Macro_Etape") - self.macroitem=macroitem - self.jdc=macroitem.object.jdc_aux - self.nom_jdc=nom_jdc - self.appli=appli - self.barre=Tkinter.Frame(self.fenetre,relief="ridge",bd=2) - self.barre.pack(expand=0,fill=Tkinter.X) - if self.macroitem.object.fichier_text is not None: - b=Tkinter.Button(self.barre,image=images.get_image("Zoom24"),command=self.visufile) - b.pack(side='left') - tp=tooltip.TOOLTIP(b,"View file") - self.mainPart=Pmw.ScrolledCanvas(self.fenetre, - hull_width=600, - hull_height=500, - borderframe=1) - self.canvas=self.mainPart.component('canvas') - Pmw.Color.changecolor(self.canvas,background='gray95') - self.mainPart.pack(padx=10,pady=10,fill = 'both', expand = 1) - self.item=MACRO2TreeItem(self.appli,nom_jdc,self.jdc) - self.tree = treewidget.Tree(self.appli,self.item,self.mainPart,command=None,rmenu=self.make_rmenu) - self.tree.draw() - CONNECTOR.Connect(self.jdc,"close",self.onCloseView,()) - - def onCloseView(self): - self.quit() - - def visufile(self): - Fenetre(self.appli,titre="Source du fichier inclus",texte=self.macroitem.object.fichier_text) - - def make_rmenu(self,node,event): - if hasattr(node.item,'rmenu_specs'): - rmenu = Tkinter.Menu(self.canvas, tearoff=0) - self.cree_menu(rmenu,node.item.rmenu_specs,node) - rmenu.tk_popup(event.x_root,event.y_root) - - def cree_menu(self,menu,itemlist,node): - """ - Ajoute les items du tuple itemlist - dans le menu menu - """ - number_item=0 - radio=None - for item in itemlist: - number_item=number_item + 1 - if not item : - menu.add_separator() - else: - label,method=item - if type(method) == types.TupleType: - # On a un tuple => on cree une cascade - menu_cascade=Tkinter.Menu(menu) - menu.add_cascade(label=label,menu=menu_cascade) - self.cree_menu(menu_cascade,method,node) - elif method[0] == '&': - # On a une chaine avec & en tete => on cree un radiobouton - try: - command=getattr(node.item,method[1:]) - menu.add_radiobutton(label=label,command=lambda a=self.appli,c=command,n=node:c(a,n)) - if radio == None:radio=number_item - except:pass - else: - try: - command=getattr(node.item,method) - menu.add_command(label=label,command=lambda a=self.appli,c=command,n=node:c(a,n)) - except:pass - # Si au moins un radiobouton existe on invoke le premier - if radio:menu.invoke(radio) - - def quit(self): - #print "quit",self - self.tree.supprime() - self.tree=None - self.fenetre.destroy() - - #def __del__(self): - # print "__del__",self - -def makeMacroDisplay(appli,macroitem,nom_item): - return MacroDisplay(appli,macroitem,nom_item) - -import treeitemincanvas - -class TREEITEMINCANVAS(treeitemincanvas.TREEITEMINCANVAS): - def __init__(self,object,nom="",parent=None,appli=None,sel=None,rmenu=None): - #print "TREEITEMINCANVAS",object - self.object=object - self.nom=nom - self.appli=appli - self.parent=parent - - self.item=MACRO2TreeItem(self.appli,self.nom,self.object) - self.canvas=Pmw.ScrolledCanvas(self.parent,borderframe=1,canvas_background='gray95') - self.canvas.pack(padx=10,pady=10,fill = 'both', expand = 1) - if not sel: - def sel(event=None): - return - self.tree=treewidget.Tree(self.appli,self.item,self.canvas,command=sel,rmenu=rmenu) - self.tree.draw() - -import jdcdisplay - -class MACRODISPLAY(jdcdisplay.JDCDISPLAY): - def __init__(self,jdc,nom_jdc,appli=None,parent=None): - #print "MACRODISPLAY",jdc - self.jdc=jdc - self.nom_jdc=nom_jdc - self.fichier=None - self.panel_courant=None - self.appli=appli - self.parent=parent - self.node_selected = None - self.modified='n' - - self.pane=Pmw.PanedWidget(self.parent,orient='horizontal') - self.pane.add('treebrowser',min=0.4,size=0.5) - self.pane.add('selected',min=0.4) - self.pane.pack(expand=1,fill='both') - self.tree=TREEITEMINCANVAS(jdc,nom_jdc,self.pane.pane('treebrowser'), - self.appli,self.select_node,self.make_rmenu) - diff --git a/InterfaceTK/menubar.py b/InterfaceTK/menubar.py deleted file mode 100644 index 119bbdfa..00000000 --- a/InterfaceTK/menubar.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -""" -""" -from Tkinter import Menu - -class MENUBAR: - def __init__(self,appli,parent): - # L'attribut appli pointe vers l'objet application qui détient la menubar et les autres composants - self.appli=appli - # L'attribut parent pointe vers l'objet graphique parent de la menubar - self.parent=parent - self.menubar=Menu(self.parent) - self.parent.configure(menu=self.menubar) - self.init() - - try: - from prefs import labels - except: - labels= ('Fichier','Edition','Jeu de commandes','Catalogue','Options','Aide','Traduction') - - def init(self): - self.menudict={} - for label in self.labels: - menu=Menu(self.menubar,tearoff=0) - self.menudict[label]=menu - self.menubar.add_cascade(label=label,menu=menu) - diff --git a/InterfaceTK/newsimppanel.py b/InterfaceTK/newsimppanel.py deleted file mode 100644 index 77ca83aa..00000000 --- a/InterfaceTK/newsimppanel.py +++ /dev/null @@ -1,196 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -# Modules Python -import string,types,os -from Tkinter import * -import Pmw -from copy import copy,deepcopy -import traceback - -# Modules Eficas -from Editeur import Objecttreeitem -import prefs -import panels -import images -import composimp -from widgets import ListeChoix -from widgets import FenetreDeSelection - -from Noyau.N_CR import justify_text -from Editeur.utils import substract_list - - -class newSIMPPanel(panels.OngletPanel): - """ - Classe virtuelle servant de classe mère à toutes les classes Panel - servant à afficher et récupérer la valeur d'un mot-clé simple. - Le panel est différent suivant le type de la valeur attendu - """ - def init(self): - """ - Méthode appelée par le constructeur de OngletPanel : - construit le notebook à 2 onglets utilisé par tous les panels de - tous les mots-clés simples - """ - nb = Pmw.NoteBook(self,raisecommand=self.raisecmd) - nb.pack(fill = 'both', expand = 1) - self.nb=nb - nb.add('Valeur', tab_text='Saisir valeur') - self.makeValeurPage(nb.page('Valeur')) - self.enlevebind() - self.creebind() - nb.setnaturalsize() - -# ---------------------------------------------------------------------------------------- -# Méthodes utilisées pour l'affectation de la valeur donnée par l'utilisateur -# au mot-clé courant -# ---------------------------------------------------------------------------------------- - - def reset_old_valeur(self,name=None,mess='Valeur du mot-clé enregistrée'): - """ - Enregistre val comme valeur de self.node.item.object SANS - faire de test de validité ni ré-évaluer l'ancienne valeur - permet de rester avec des valeurs non entrees et de ne pas - ré-évaluer des entiers par exemple - """ - if self.parent.modified == 'n' : self.parent.init_modif() - self.node.item.set_valeur(name) - self.parent.appli.affiche_infos(mess) - - def record_valeur(self,name=None,mess='Valeur du mot-clé enregistrée'): - """ - Enregistre val comme valeur de self.node.item.object - en evaluant l item et en le validant - Si name n'est pas renseigné, la valeur - """ - if self.parent.modified == 'n' : self.parent.init_modif() - if name != None: - valeur = name - validite = 1 - else : - valeurentree= self.entry.get() - self.entry.delete(0,END) - if valeurentree == '': valeurentree=None - valeur,validite=self.node.item.eval_valeur(valeurentree) - if not validite : - valeur= self.entry.get() - commentaire = "impossible d'évaluer : %s " %`valeurentree` - self.parent.appli.affiche_infos(commentaire) - - if validite : - validite,commentaire=self.node.item.valide_val(valeur) - - if validite : - self.node.item.set_valeur(valeur) - self.parent.appli.affiche_infos(mess) - else : - self.parent.appli.affiche_infos(commentaire) - -# ---------------------------------------------------------------------------------------- -# Méthodes utilisées pour la manipulation des items dans les listes de choix -# ---------------------------------------------------------------------------------------- - def selectValeur(self,name): - self.selected_valeur = name - - def deselectValeur(self,name): - self.selectValeur = None - - def sup_valeur(self,name=None): - """ - Supprime la valeur selectionnée de la liste des valeurs et la rajoute - à la liste des choix possibles - """ - if hasattr(self,'selected_valeur') : - if ( self.selected_valeur != None and self.selected_valeur != ''): - liste_valeurs = self.Liste_valeurs.get_liste() - liste_valeurs.remove(self.selected_valeur) - self.Liste_valeurs.put_liste(liste_valeurs) - listeActuelle=self.Liste_valeurs.get_liste() - liste_choix=self.node.item.get_liste_possible(listeActuelle) - self.Liste_choix.put_liste(liste_choix) - self.selected_valeur = None - - def add_choix(self,name=None): - """ - Ajoute le choix selectionné à la liste des valeurs et le retire - de la liste des choix possibles - """ - - if hasattr(self,'selected_choix') : - if (self.selected_choix != None and self.selected_choix != ''): - min,max = self.node.item.GetMinMax() - liste_valeurs = self.Liste_valeurs.get_liste() - if len(liste_valeurs) >= max : - self.parent.appli.affiche_infos("La liste ne peut pas avoir plus de %d éléments" %max) - return - if (self.Liste_valeurs.selection != None): - ligne=self.Liste_valeurs.cherche_selected_item() - liste_valeurs.insert(ligne,self.selected_choix) - else : - liste_valeurs.append(self.selected_choix) - self.Liste_valeurs.put_liste(liste_valeurs) - listeActuelle=self.Liste_valeurs.get_liste() - liste_choix=self.node.item.get_liste_possible(listeActuelle) - self.Liste_choix.put_liste(liste_choix) - self.selected_choix = None - - def selectChoix(self,name): - self.selected_choix = name - - def deselectChoix(self,name): - self.selectChoix = None - - def raisecmd(self,page): - try: - self.entry.focus() - except: - pass - -# ---------------------------------------------------------------------------------------- -# Méthodes utilisées pour la manipulation des items en notation scientifique -# ---------------------------------------------------------------------------------------- - def set_valeur_texte(self,texte_valeur) : - """ Sert à mettre à jour la notation scientifique""" - try : - if "R" in self.node.item.object.definition.type: - if texte_valeur[0] != "'": - clef=eval(texte_valeur) - if str(clef) != str(texte_valeur) : - self.node.item.object.init_modif() - clefobj=self.node.item.object.GetNomConcept() - if not self.parent.appli.dict_reels.has_key(clefobj): - self.parent.appli.dict_reels[clefobj] = {} - self.parent.appli.dict_reels[clefobj][clef]=texte_valeur - self.parent.appli.dict_reels[clefobj] - self.node.item.object.fin_modif() - except: - pass - - - def get_valeur_texte(self,valeur) : - valeur_texte="" - if "R" in self.node.item.object.definition.type: - clefobj=self.node.item.object.GetNomConcept() - if self.parent.appli.dict_reels.has_key(clefobj): - if self.parent.appli.dict_reels[clefobj].has_key(valeur): - valeur_texte=self.parent.appli.dict_reels[clefobj][valeur] - return valeur_texte - diff --git a/InterfaceTK/options.py b/InterfaceTK/options.py deleted file mode 100644 index 9d0da1e4..00000000 --- a/InterfaceTK/options.py +++ /dev/null @@ -1,132 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -""" -""" -# Modules Python -import os,string - -# Modules Eficas -from widgets import askopenfilename -import panels - -# l'option affichage_commandes peut prendre les valeurs "groupes" ou "alphabetic" -affichage_commandes="alphabetic" - -class OPTIONS: - - menu_defs=[ - ('Options',[ - ("Affichage commandes",(("alphabétique",'&affichage_alpha'),("groupes",'&affichage_grp'))), - #("Couleur",(("fond",'change_fond'),("barre",'change_barre'))), - # ("Catalogue développeur",'choix_cata_developpeur'), - ('Paramètres Eficas','affichage_fichier_ini'), - ('Paramètres Affichage','affichage_style_ini'), - - ] - ) - ] - - button_defs=[] - - def __init__(self,appli,parent): - self.appli=appli - self.parent=parent - - - def affichage_grp(self): - global affichage_commandes - affichage_commandes="groupes" - if hasattr(panels,'panneauCommande'): - panel=panels.panneauCommande - parent=panel.parent - if parent != None : - parent.create_panel(parent.node_selected) - # si on a un panel avec plusieurs onglets - # on affiche Commande - try : - parent.panel_courant.nb.selectpage("Commande") - except : - pass - - def affichage_alpha(self): - - global affichage_commandes - affichage_commandes="alphabetic" - if hasattr(panels,'panneauCommande'): - panel=panels.panneauCommande - parent=panel.parent - if parent != None : - parent.create_panel(parent.node_selected) - # si on a un panel avec plusieurs onglets - # on affiche Commande - try : - parent.panel_courant.nb.selectpage("Commande") - except : - pass - - def change_fond(self): - from tkColorChooser import askcolor - #nouvelle=askcolor(self.appli.background) - nouvelle=askcolor('grey') - - def change_barre(self): - pass - - def choix_cata_developpeur(self): - """ - Cette méthode demande à l'utilisateur-développeur d'indiquer quel catalogue - il veut utiliser en remplacement du catalogue standard du code - NB : il faut que le développeur ait les droits d'écriture dans le répertoire où - se trouve le catalogue - """ - file = askopenfilename(title="Choix d'un catalogue personnel", - defaultextension=".py", - filetypes = ( ("Catalogue", "cata*.py"),)) - if file : - self.parent.update_idletasks() - self.appli.reset_affichage_infos() - rep_fic = os.path.dirname(file) - nom_fic = string.split(os.path.basename(file),'.')[0] - rep_courant = os.getcwd() - os.chdir(rep_fic) - self.cata = __import__(nom_fic) - self.code = self.cata.CODE - os.chdir(rep_courant) - self.fic_cata = file - fic_cata_p = nom_fic+'_pickled.py' - self.fic_cata_p = os.path.join(rep_fic,fic_cata_p) - pile_erreurs = self.cata.erreurs_cata - if pile_erreurs.existe_message() : - messages = pile_erreurs.retourne_messages() - print messages - else : - # XXX ne doit pas fonctionner - self.catalo = catabrowser.CataItem(cata=self.cata) - self.Retrouve_Ordre_Cata('personnel') - pile_erreurs.efface() - - - def affichage_fichier_ini(self): - self.appli.CONFIGURATION.affichage_fichier_ini() - - - def affichage_style_ini(self): - self.appli.CONFIGStyle.affichage_style_ini() diff --git a/InterfaceTK/panels.py b/InterfaceTK/panels.py deleted file mode 100644 index b84a5697..00000000 --- a/InterfaceTK/panels.py +++ /dev/null @@ -1,587 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -import string -import os -from Tkinter import * -import Pmw -import time -import traceback - -import widgets -from widgets import ListeChoix -from widgets import ListeChoixParGroupes -import prefs -import options - -SEPARATEUR = '-'*30 - - -class Panel(Frame) : - """ - Classe servant de classe mère à toutes celles représentant les - panneaux à afficher en fonction de la nature de l'objet en cours - Elle est toujours dérivée. - """ - def __init__(self,parent,panneau,node) : - # Le parent d'un panel est un objet de la classe JDCDISPLAY ou derivee - # ou un objet qui a les attributs : appli (de classe APPLI ou derivee), - # modified et la methode init_modif - self.parent=parent - self.panneau = panneau - self.node=node - Frame.__init__(self,self.panneau) - self.place(x=0,y=0,relheight=1,relwidth=1) - self.creer_boutons() - self.init() - global panneauCommande - panneauCommande=self - - #def __del__(self): - # print "__del__",self - - def update_panel(self): - """Methode appele pour demander une mise a jour du panneau""" - - def destroy(self): - Frame.destroy(self) - self.panneau=None - self.parent=None - # Because on herite de Frame - self.master=None - # On supprime explicitement les references aux objets Tk - self.nb=None - self.fr_but=None - self.bouton_cata=None - self.bouton_doc=None - self.bouton_com=None - self.bouton_sup=None - #self.frame_eval=None - self.label=None - self.frame_boutons=None - self.frame_comment=None - self.frame_param=None - # On termine la suppression de facon brutale (objets Tk et non Tk) - for k in self.__dict__.keys(): - # il est plus prudent de ne pas détruire le lien sur le Node - # si on voulait mettre l'attribut node à None, il faudrait - # que tous les appels à node.parent.select() apparaissent après - # toutes les autres actions liées au panel (node.item.isglobal(), ...) - if k != 'node' : setattr(self,k,None) - - def creer_boutons(self): - """ - Méthode créant les boutons se trouvant dans la partie contextuelle d'EFICAS - (à droite sous les onglets ) - """ - self.fr_but = Frame(self,height=30) - self.fr_but.pack(side='bottom') - self.bouton_com = Button(self.fr_but, text = 'Commentariser', command = self.ajout_commentaire) - self.bouton_sup = Button(self.fr_but, text = "Supprimer", command=self.supprimer) - self.bouton_doc = Button(self.fr_but, text="Documentation", command=self.visu_doc) - self.bouton_cata = Button(self.fr_but, text = "Catalogue", command = self.show_catalogue) - - if self.parent.appli.CONFIGURATION.isdeveloppeur == 'OUI': - self.bouton_sup.pack(side='left',padx=5, pady=5) - self.bouton_cata.pack(side='left',padx=5, pady=5) - self.bouton_doc.pack(side='right',padx=5, pady=5) - #self.bouton_sup.place(relx=0.25,rely = 0.5,relheight = 0.8,anchor='center') - #self.bouton_cata.place(relx=0.5,rely = 0.5,relheight = 0.8,anchor='center') - #self.bouton_doc.place(relx=0.75,rely = 0.5,relheight = 0.8,anchor='center') - else: - self.bouton_sup.pack(side='left',padx=5, pady=5) - self.bouton_doc.pack(side='right',padx=5, pady=5) - #self.bouton_sup.place(relx=0.3,rely = 0.5,relheight = 0.8,anchor='center') - #self.bouton_doc.place(relx=0.7,rely = 0.5,relheight = 0.8,anchor='center') - - def show_catalogue(self): - try: - genea = self.node.item.get_genealogie() - self.parent.appli.browser_catalogue_objet(genea) - except Exception,e: - traceback.print_exc() - - def efface(self): - self.node.efface() - -# ------------------------------------------------------------------------ -# Méthodes permettant d'ajouter des commentaires, des paramètres -# et des objets EVAL. -# Ces méthodes sont utilisées par les panneaux des JDC,ETAPE, -# COMMENTAIRE et PARAMETRE -# ------------------------------------------------------------------------ - - def ajout_commentaire(self,ind='after'): - """ - Ajoute un commentaire à l'intérieur du JDC : - - si ind='after' : l'ajoute après l'objet courant - - si ind='before' : l'ajoute avant. - """ - if self.parent.modified == 'n' : self.parent.init_modif() - return self.node.append_brother("COMMENTAIRE",ind) - - def ajout_commentaire_first(self): - """ - Ajoute un commentaire en début de JDC - """ - if self.parent.modified == 'n' : self.parent.init_modif() - return self.node.append_child("COMMENTAIRE",'first') - - def ajout_parametre(self,ind='after'): - """ - Ajoute un parametre à l'intérieur du JDC : - - si ind='after' : l'ajoute après l'objet courant - - si ind='before' : l'ajoute avant. - """ - if self.parent.modified == 'n' : self.parent.init_modif() - return self.node.append_brother("PARAMETRE",ind) - - def ajout_parametre_first(self): - """ - Ajoute un parametre en début de JDC - """ - if self.parent.modified == 'n' : self.parent.init_modif() - return self.node.append_child("PARAMETRE",'first') - -# def ajout_parametre_eval(self,ind='after'): -# """ -# Ajoute un paramètre EVAL à l'intérieur du JDC : -# - si ind='after' : l'ajoute après l'objet courant -# - si ind='before' : l'ajoute avant. -# """ -# if self.parent.modified == 'n' : self.parent.init_modif() -# return self.node.append_brother("PARAMETRE_EVAL",ind) - -# def ajout_parametre_eval_first(self): -# """ -# Ajoute un paramètre EVAL en début de JDC -# """ -# if self.parent.modified == 'n' : self.parent.init_modif() -# return self.node.append_child("PARAMETRE_EVAL",'first') - -# ------------------------------------------------------------------------ - - def visu_doc(self): - """ Permet d'ouvrir le fichier doc U de la commande au format pdf avec Acrobat Reader - - Ne fonctionne pas sous UNIX (chemin d'accès Acrobat Reader) - - indication du chemin d'accès aux fichiers pdf à revoir : trop statique""" - cle_doc = self.node.item.get_docu() - if cle_doc == None : return - cle_doc = string.replace(cle_doc,'.','') - cle_doc = string.replace(cle_doc,'-','') - commande = self.parent.appli.CONFIGURATION.exec_acrobat - nom_fichier = cle_doc+".pdf" - fichier = os.path.abspath(os.path.join(self.parent.appli.CONFIGURATION.path_doc, - nom_fichier)) - if os.name == 'nt': - os.spawnv(os.P_NOWAIT,commande,(commande,fichier,)) - elif os.name == 'posix': - script ="#!/usr/bin/sh \n%s %s&" %(commande,fichier) - pid = os.system(script) - - def supprimer(self): - """ - Suppression du noeud courant - """ - # On signale au parent du panel (le JDCDisplay) une modification - self.parent.init_modif() - self.node.delete() - - def affiche(self): - """ Force l'affichage des fenêtres en cours """ - self.tkraise() - - def selectMC(self,name): - """ On retrouve le mot-clé sous le curseur pour affichage du fr """ - cmd=self.node.item.get_definition() - texte_infos = '' - for e in cmd.entites.keys() : - if e == name : - texte_infos=getattr(cmd.entites[e],prefs.lang) - break - if texte_infos == '' : texte_infos="Pas d'infos disponibles" - self.parent.appli.affiche_infos(texte_infos) - - def defMC(self,name): - """ On ajoute un mot-clé à la commande : subnode """ - if name == SEPARATEUR:return - if self.parent.modified == 'n' : self.parent.init_modif() - if name != "COMMENTAIRE": - self.node.append_child(name) - else : - self.ajout_commentaire() - - def selectCmd(self,name): - """ On retrouve la commande sous le curseur pour affichage du fr """ - if name != 'COMMENTAIRE' and name != SEPARATEUR: - texte_infos=getattr(self.parent.jdc.get_cmd(name),prefs.lang) - self.parent.appli.affiche_infos(texte_infos) - - def defCmd(self,name): - """ - On ajoute une commande après la commande selectionnée : after - ou bien on ajoute un commentaire - """ - if name == SEPARATEUR:return - if self.parent.modified == 'n' : self.parent.init_modif() - if name != "COMMENTAIRE": - #parent=self.node.parent - #new_obj = parent.item.append_child(name,self.node.item.getObject()) - #parent.children[parent.children.index(self.node)+1].select() - new_node = self.node.append_brother(name,'after') - else : - new_node = self.ajout_commentaire() - - def defCmdFirst(self,name): - """ On ajoute une commande ou un commentaire au début du fichier de commandes """ - if name == SEPARATEUR:return - if self.parent.modified == 'n' : self.parent.init_modif() - if name != "COMMENTAIRE": - #new_obj = self.node.item.append_child(name,'first') - #self.node.children[0].select() - new_node = self.node.append_child(name,'first') - else : - new_node = self.ajout_commentaire_first() - -class OngletPanel(Panel) : - """ Cette classe est virtuelle et doit être dérivée - Elle contient les principales méthodes d'affichage des différents onglets""" - - global panelbind - - def raisecmd(self,page): - self.nb.page(page).focus_set() - if page == 'Concept': - try: - self._any.focus() - except: - pass - elif page == 'Commande': - try: - self.command_entry.component('entry').focus() - except: - pass - - def creebind(self): - self.nb.bind_all("",lambda e,s=self,num=0:s.commande_up(num)) - self.nb.bind_all("",lambda e,s=self,num=1:s.commande_up(num)) - self.nb.bind_all("",lambda e,s=self,num=2:s.commande_up(num)) - self.nb.bind_all("",lambda e,s=self,num=3:s.commande_up(num)) - OngletPanel.panelbind=self.nb - - def enlevebind(self): - if not hasattr(OngletPanel,"panelbind"): - return - if OngletPanel.panelbind == None: - return - try: - OngletPanel.panelbind.unbind_all("") - OngletPanel.panelbind.unbind_all("") - OngletPanel.panelbind.unbind_all("") - OngletPanel.panelbind.unbind_all("") - except: - pass - OngletPanel.panelbind = None - - def commande_up(self,num): - #print "commande_up de panels pour ", num - try : - OngletPanel.panelbind.selectpage(num) - pageNew=OngletPanel.panelbind.page(num) - pageNew.focus_set() - except : - pass - - def affiche(self): - page=self.nb.getcurselection() - self.nb.page(page).focus_set() - if page == 'Concept': - try: -# _any est un pointeur sur entry -# component est une methode de pmw -# a priori, jamais ok - self._any.component('entry').focus_set() - except: - pass - self.tkraise() - -# ------------------------------------------------------------------------ -# Méthodes permettant d'afficher des pages partagées par différents -# types d'objets (règles,mots-clés,concept,...) -# ------------------------------------------------------------------------ - - def makeConceptPage(self,page): - """ - Crée la page de saisie du nom du concept - """ - self.label = Label(page,text='Nom du concept :') - self.label.place(relx=0.1,rely=0.4) - self._any = Entry(page,relief='sunken') - self._any.place(relx=0.35,rely=0.4,relwidth=0.5) - self._any.bind("",lambda e,s=self:s.execConcept()) - self._any.bind("",lambda e,s=self:s.execConcept()) - self._any.insert(0,self.node.item.GetText()) - self.but_ok=Button(page,text = "Valider",command=self.execConcept) - self.but_ok.place(relx=0.35,rely=0.8, relwidth=0.35) - type_sd = self.node.item.get_type_sd_prod() - if type_sd : - txt = "L'opérateur courant retourne un objet de type %s" %type_sd - self.label = Label(page, text = txt) - self.label.place(relx=0.5,rely=0.55,anchor='n') - self._any.focus() - # aide associée au panneau - bulle_aide="""Tapez dans la zone de saisie le nom que vous voulez donner - au concept retounré par l'opérateur courant et pressez pour valider""" - page.bind("", lambda e,s=self,a=bulle_aide : s.parent.appli.affiche_aide(e,a)) - page.bind("",self.parent.appli.efface_aide) - - - def makeMoclesPage(self,page): - """ - Crée la page qui affiche la liste des mots-clés que l'on peut - encore ajouter - """ - genea =self.node.item.get_genealogie() - jdc = self.node.item.get_jdc() - liste_mc=self.node.item.get_liste_mc_ordonnee(genea,jdc.cata_ordonne_dico) - liste_commandes = (("",self.selectMC), - ("",self.deselectMC), - ("",self.defMC)) - Liste = ListeChoix(self,page,liste_mc,liste_commandes = liste_commandes,titre = "Mots-clés permis",optionReturn="oui") - Liste.affiche_liste() - # aide associée au panneau - bulle_aide="""Double-cliquez sur le mot-clé que vous voulez ajouter à - la commande en cours d'édition""" - Liste.MCbox.bind("", lambda e,s=self,a=bulle_aide : s.parent.appli.affiche_aide(e,a)) - Liste.MCbox.bind("",self.parent.appli.efface_aide) - if len(liste_mc) > 0 : - Liste.surligne(liste_mc[0]) - self.Liste=Liste - - def makeCommentairePage(self,page): - label = Label(page,text = "Insérer un commentaire :") - label.grid(column = 0, row = 2) - but_avant = Button(page,text = "AVANT",command = lambda s=self :s.ajout_commentaire(ind = 'before')) - but_apres = Button(page,text = "APRES",command = self.ajout_commentaire) - but_avant.grid(column = 1,row =2) - but_apres.grid(column = 1,row =3) - - def makeCommandePage(self,page): - """ - Cree l'onglet - """ - frame1 = Frame(page,height = 20) - frame1.pack(side='top',fill='x') - label = Label(frame1,text ="La commande choisie sera ajoutée\n APRES la commande courante") - label.pack(side='top') - frame2 = Frame(page) - frame2.pack(side='top',fill='both',expand=1) - liste_commandes = (("",self.selectCmd), - ("",self.deselectCmd), - ("",self.defCmd)) - if options.affichage_commandes == "alphabetic": - liste_cmd = self.get_liste_cmd() - Liste = ListeChoix(self,frame2,liste_cmd,liste_commandes = liste_commandes, - filtre='oui',titre = "Commandes",optionReturn="oui") - else: - liste_commandes=liste_commandes+(("",self.defCmd),) - liste_groupes,dict_groupes=self.get_groups() - Liste = ListeChoixParGroupes(self,frame2,liste_groupes,dict_groupes, - liste_commandes = liste_commandes, - filtre='oui',titre = "Commandes",optionReturn="oui") - Liste.affiche_liste() - self.command_entry=Liste.entry - # aide associée au panneau - bulle_aide="""Double-cliquez sur la commande que vous voulez ajouter au jeu de commandes""" - Liste.MCbox.bind("", lambda e,s=self,a=bulle_aide : s.parent.appli.affiche_aide(e,a)) - Liste.MCbox.bind("",self.parent.appli.efface_aide) - self.liste_command=Liste - global panneauCommande - panneauCommande=self - - def makeJDCPage(self,page): - """ - Crée la page correspondant à un objet de type JDC - """ - liste_commandes = (("",self.selectCmd), - ("",self.deselectCmd), - ("",self.defCmdFirst)) - if options.affichage_commandes == "alphabetic": - liste_cmd = self.get_liste_cmd() - Liste = ListeChoix(self,page,liste_cmd,liste_commandes = liste_commandes, - filtre='oui',titre = "Commandes",optionReturn="oui") - else: - liste_commandes=liste_commandes+(("",self.defCmdFirst),) - liste_groupes,dict_groupes=self.get_groups() - Liste = ListeChoixParGroupes(self,page,liste_groupes,dict_groupes, - liste_commandes = liste_commandes, - filtre='oui',titre = "Commandes",optionReturn="oui") - Liste.affiche_liste() - # aide associée au panneau - bulle_aide="""Double-cliquez sur la commande que vous voulez ajouter au jeu de commandes""" - Liste.MCbox.bind("", lambda e,s=self,a=bulle_aide : s.parent.appli.affiche_aide(e,a)) - Liste.MCbox.bind("",self.parent.appli.efface_aide) - - def makeReglesPage(self,page) : - """ - Crée la page qui affiche la liste des règles avec celle qui ne sont - pas respectées en rouge - """ - regles = [] - regles = self.node.item.get_regles() - dictionnaire = self.node.item.get_mc_presents() - texte_regles = [] - l_regles_en_defaut=[] - if len(regles) > 0: - i = 0 - for regle in regles : - texte_regles.append(regle.gettext()) - texte,test = regle.verif(dictionnaire) - if test == 0 : l_regles_en_defaut.append(i) - i = i+1 - Liste = ListeChoix(self,page,texte_regles,liste_marques=l_regles_en_defaut,active='non',titre="Règles") - Liste.affiche_liste() - # aide associée au panneau - bulle_aide="""Ce panneau contient la liste des règles qui s'appliquent à l'objet - en cours d'édition. - - en noir : règles valides - - en rouge : règles violées""" - Liste.MCbox.bind("", lambda e,s=self,a=bulle_aide : s.parent.appli.affiche_aide(e,a)) - Liste.MCbox.bind("",self.parent.appli.efface_aide) - - def makeParamCommentPage_for_etape(self,page): - """ - Crée la page qui offre le choix à l'utilisateur d'ajouter un commentaire - ou un paramètre, avant ou après le noeud courant dans l'arbre. - Cette page est destinée aux objets de niveau ETAPE cad à toutes les CMD, - les commentaires inter commandes et les paramètres - """ - # les frame ... - self.frame_comment = Frame(page,bd=1,relief='raised') - self.frame_param = Frame(page,bd=1,relief='raised') - self.frame_boutons = Frame(page,bd=1,relief='raised') - self.frame_comment.place(relx=0,rely=0,relwidth=1,relheight=0.40) - self.frame_param.place(relx=0,rely=0.40,relwidth=1,relheight=0.40) - self.frame_boutons.place(relx=0,rely=0.84,relwidth=1,relheight=0.16) - # remplissage de la frame commentaire - Label(self.frame_comment,text = "Insérer un commentaire :").place(relx=0.1,rely=0.5,anchor='w') - but_comment_avant = Button(self.frame_comment, - text = "AVANT "+self.node.item.get_nom(), - command = lambda s=self :s.ajout_commentaire(ind = 'before')) - but_comment_apres = Button(self.frame_comment, - text = "APRES "+self.node.item.get_nom(), - command = self.ajout_commentaire) - but_comment_avant.place(relx=0.45,rely=0.3,anchor='w',relwidth=0.45) - but_comment_apres.place(relx=0.45,rely=0.7,anchor='w',relwidth=0.45) - # remplissage de la frame paramètre - Label(self.frame_param,text = "Insérer un paramètre :").place(relx=0.1,rely=0.5,anchor='w') - but_param_avant = Button(self.frame_param, - text = "AVANT "+self.node.item.get_nom(), - command = lambda s=self :s.ajout_parametre(ind = 'before')) - but_param_apres = Button(self.frame_param, - text = "APRES "+self.node.item.get_nom(), - command = self.ajout_parametre) - but_param_avant.place(relx=0.45,rely=0.3,anchor='w',relwidth=0.45) - but_param_apres.place(relx=0.45,rely=0.7,anchor='w',relwidth=0.45) - # remplissage de la frame boutons - Button(self.frame_boutons, - text="Commentariser toute la commande", - command = self.comment_commande).place(relx=0.5,rely=0.5,anchor='center') - - def deselectMC(self,name): - self.parent.appli.affiche_infos('') - - def get_groups(self): - jdc=self.node.item.object.get_jdc_root() - return jdc.get_groups() - - def get_liste_cmd(self): - #print "get_liste_cmd",self.node.item.object - jdc=self.node.item.object.get_jdc_root() - listeCmd = jdc.get_liste_cmd() - return listeCmd - - def deselectCmd(self,name): - self.parent.appli.affiche_infos('') - - def execConcept(self): - """ - Nomme le concept SD retourné par l'étape - """ - if not hasattr(self,'valeur_choisie'): - nom = self._any.get() - else: - nom = self.valeur_choisie.get() - nom = string.strip(nom) - if nom == '' : return # si pas de nom, on ressort sans rien faire ... - if self.parent.modified == 'n' : self.parent.init_modif() - test,mess = self.node.item.nomme_sd(nom) - #self.node.verif() - #self.node.racine.update() - self.parent.appli.affiche_infos(mess) - - def changed(self): - pass - - def comment_commande(self): - """ - Cette méthode a pour but de commentariser la commande pointée par self.node - """ - # On traite par une exception le cas où l'utilisateur final cherche à désactiver - # (commentariser) un commentaire. - try : - pos=self.node.parent.children.index(self.node) - commande_comment = self.node.item.get_objet_commentarise() - # On signale au parent du panel (le JDCDisplay) une modification - self.parent.init_modif() - self.node.parent.children[pos].select() - except Exception,e: - traceback.print_exc() - widgets.showerror("TOO BAD",str(e)) - return - - -class Panel_Inactif(Panel): - """ - Cette classe sert à définir un panneau dans lequel on dit que le noeud - sélectionné n'est pas actif - """ - def __init__(self,parent,panneau,node) : - self.parent=parent - self.panneau = panneau - self.node=node - Frame.__init__(self,self.panneau) - self.place(x=0,y=0,relheight=1,relwidth=1) - self.creer_texte() - - def creer_texte(self): - texte = "Le noeud sélectionné ne correspond pas à un objet actif\n" - texte = texte + "Seules les commandes placées entre \nDEBUT/POURSUITE et FIN sont actives" - longueur = int(self.panneau.winfo_width()*0.8) - self.label = Label(self,text=texte,wraplength=longueur,justify='center') - self.label.place(relx=0.5,rely=0.4,relwidth=0.8,anchor='center') - self.bouton_sup = Button(self, - text = "Supprimer", - command=self.supprimer, - width=14) - self.bouton_sup.place(relx=0.5,rely=0.8,anchor='center') - - -if __name__ == "__main__" : pass diff --git a/InterfaceTK/panelsSalome.py b/InterfaceTK/panelsSalome.py deleted file mode 100644 index 800848ed..00000000 --- a/InterfaceTK/panelsSalome.py +++ /dev/null @@ -1,286 +0,0 @@ -# -*- coding: utf-8 -*- - -from Tkinter import * -from widgets import ListeChoix -from widgets import showerror - -from fonctionpanel import FONCTION_Panel -from shellpanel import SHELLPanel -from plusieursintopanel import PLUSIEURS_INTO_Panel -from plusieursassdpanel import PLUSIEURS_ASSD_Panel -from plusieursbasepanel import PLUSIEURS_BASE_Panel -from plusieursbasepanel import PLUSIEURS_BASE_OR_UNELISTE_Panel -from uniquesdcopanel import UNIQUE_SDCO_Panel -from uniqueassdpanel import UNIQUE_ASSD_Panel -from uniqueintopanel import UNIQUE_INTO_Panel -from uniquecomppanel import UNIQUE_COMP_Panel -from uniquebasepanel import UNIQUE_BASE_Panel -from uniqueassdpanel import UNIQUE_ASSD_Panel_Reel - -from Noyau.N_CR import justify_text - -import traceback -import images - - - -# 2 types de commandes vont etre particularisees dans Salome -# -# - un cas general : -# Toutes les commandes possedant GROUP_NO ou GROUP_MA -# seront surchargees d office -# pour cela on va utiliser le dictionnaire dict_classes_salome -# qui va permettre de changer la classe de la commande -# ainsi si un panel en dehors de salome a pour classe PLUSIEURS_BASE_Panel -# la classe de ce panel devient alors SALOME_PLUSIEURS_BASE_Panel -# (pour cela voir composimp) - -# des commandes "autres" ne pouvant pas etre identifiées par leur nom -# il suffit de creer dans la classe SALOME de la commande -# une fonction portant son nom -# Exemple de particularisation d un panel : -# Supposons que l on veuille particulariser la commande -# - LIRE_MAILLAGE_UNITE -# le panel initial a pour classe UNIQUE_BASE_Panel -# il suffit d'ajouter dans la classe derivée SALOME_UNIQUE_BASE_Panel -# une fonction SALOME_LIRE_MAILLAGE_UNITE -# la classe de ce panel devient alors SALOME_UNIQUE_BASE_Panel -# on peut surcharger les methodes nécessaires (affichage par exemple) - - -class SALOME_SHELLPanel (SHELLPanel): - "" - -class SALOME_FONCTION_Panel (FONCTION_Panel): - "" - -class SALOME_PLUSIEURS_INTO_Panel (PLUSIEURS_INTO_Panel): - "" - -class SALOME_PLUSIEURS_ASSD_Panel (PLUSIEURS_ASSD_Panel): - "" - -class SALOME_UNIQUE_INTO_Panel (UNIQUE_INTO_Panel): - "" - -class SALOME_UNIQUE_SDCO_Panel (UNIQUE_SDCO_Panel): - "" - -class SALOME_UNIQUE_ASSD_Panel (UNIQUE_ASSD_Panel): - "" - -class SALOME_UNIQUE_COMP_Panel (UNIQUE_COMP_Panel): - "" - -class SALOME_UNIQUE_ASSD_Panel_Reel (UNIQUE_ASSD_Panel_Reel): - "" - -# ------------------------------------------------------------------------------# -# classe SALOME_PLUSIEURS_BASE_Panel -# -# Commandes modifiées : -# - AFFE_CHAR_MECA_DDL_IMPO_GROUP_NO -# Methodes surchargées : -# - makeValeurPage(self,page) -# -# ------------------------------------------------------------------------------# - -class SALOME_PLUSIEURS_BASE_OR_UNELISTE_Panel(PLUSIEURS_BASE_OR_UNELISTE_Panel): - "" - -class SALOME_PLUSIEURS_BASE_Panel(PLUSIEURS_BASE_Panel): - - def __init__(self,parent,panneau,node): - PLUSIEURS_BASE_Panel.__init__( self, parent, panneau, node ) - #self.selected_valeur = None - - def add_valeur_plusieurs_base(self,name=None): - try: - valeur,validite,commentaire=self.get_valeur() - if not valeur: # sélection dans salome - strSelection = '' - - genea=self.node.item.get_genealogie() - kwType = None - for e in genea: - if "GROUP_NO" in e: - kwType = "GROUP_NO" - if "GROUP_MA" in e: - kwType = "GROUP_MA" - - selection, msg = self.parent.appli.selectGroupFromSalome(kwType) - if selection: - for oneSelection in selection: - strSelection +=str( oneSelection ) - strSelection +=',' - - strSelection = strSelection.rstrip(',') - self.display_valeur( strSelection ) - - PLUSIEURS_BASE_Panel.add_valeur_plusieurs_base( self, name ) - if msg: - self.parent.appli.affiche_infos(msg) - self.erase_valeur() - except: - print ' erreur add_valeur_plusieurs_base' #CS_pbruno : afficher boite de dialogue ici ? - - def makeValeurPage(self,page): - """ - Crée la page de saisie d'une liste de valeurs à priori quelconques, - cad qui ne sont pas à choisir dans une liste prédéfinie - """ - PLUSIEURS_BASE_Panel.makeValeurPage(self,page) - self.c = Button( self.frame_choix, text='Visualiser',command=self.displayInSalomeGeom ) - self.c.place( relx=0.3, rely=0.0,relwidth=0.55) - - - def displayInSalomeGeom( self ): - if self.selected_valeur: - ok, msgError = self.parent.appli.displayShape( self.selected_valeur ) - if not ok: - self.parent.appli.affiche_infos(msgError) - - - - -# ------------------------------------------------------------------------------# -# classe SALOME_UNIQUE_BASE_Panel -# -# Commandes modifiées : -# - LIRE_MAILLAGE_UNITE -# Methodes surchargées : -# - makeValeurPage(self,page) -# -# ------------------------------------------------------------------------------# - -class SALOME_UNIQUE_BASE_Panel(UNIQUE_BASE_Panel): - -# ce dictionnaire va servir lors de la sortie d efficas -# a creer le fichier qui sera integre au config.txt -# pour relier une unite logique et un nom de fichier - - dict_fichier_unite={} - - - def SALOME_DONNEES_HOMARD_FICHIER_MED_MAILLAGE_N(self): - import salome - entrychaine=salome.sg.getAllSelected() - if entrychaine != '': - self.entry2.delete(0,END) - try: - SO = salome.myStudy.FindObjectID(entrychaine[0]) - except: - boo = 0 - SO = None - - FileName='' - if SO != None: - myBuilder = salome.myStudy.NewBuilder() - boo,FileAttr = myBuilder.FindAttribute(SO,"AttributeFileType") - if boo: - val=FileAttr.Value() - if (val !="FICHIERMED" and val != "FICHIER_RESU_MED"): - boo=0 - showerror("Pas de Fichier MED","Cet Objet n a pas de fichier MED Associ\xe9") - else: - boo,FileAttr = myBuilder.FindAttribute(SO,"AttributeExternalFileDef") - if boo : - FileName=FileAttr.Value() - else: - showerror("Pas de Fichier MED","Cet Objet n a pas de fichier MED Associ\xe9") - if FileName != '' : - self.entry.delete(0,END) - self.entry2.delete(0,END) - self.entry.insert(0,FileName) - self.entry2.insert(0,FileName) - self.valid_valeur() - - - def SALOME_DONNEES_HOMARD_TRAITEMENT_NOM_MED_MAILLAGE_N(self): - import salome - EntryName='' - entrychaine=salome.sg.getAllSelected() - if entrychaine != '': - self.entry2.delete(0,END) - try: - SO = salome.myStudy.FindObjectID(entrychaine[0]) - except: - boo = 0 - SO = None - - if SO is not None: - myBuilder = salome.myStudy.NewBuilder() - ok, AtName = myBuilder.FindAttribute(SO,"AttributeName") - if ok: - EntryName=AtName.Value() - - if EntryName != '': - self.entry.delete(0,END) - self.entry2.delete(0,END) - self.entry.insert(0,EntryName) - self.entry2.insert(0,EntryName) - self.valid_valeur() - - def SALOME_DONNEES_HOMARD_FICHIER_MED_MAILLAGE_NP1(self): - self.SALOME_DONNEES_HOMARD_FICHIER_MED_MAILLAGE_N() - - def SALOME_DEFI_GROUP_CREA_GROUP_MA_GROUP_MA(self): - #try: - if ( 1 == 1 ) : - selection, msg = self.parent.appli.selectGroupFromSalome() - if selection: - strSelection =str( selection ) - UNIQUE_BASE_Panel.valid_valeur(self,strSelection) - if msg: - self.parent.appli.affiche_infos(msg) - self.erase_valeur() - #except: - else : - print ' erreur ' - - - def redistribue_selon_simp(self): - genea = self.node.item.get_genealogie() - commande="SALOME" - for i in range(0,len( genea )) : - commande=commande+"_"+ genea[i] - # -------------------------------------------------------------- - # on verifie que la methode n est pas particularise - # sinon on appelle SALOME_DEFI_GROUP_CREA_GROUP_MA_GROUP_MA qui - # sert comme methode par defaut - # -------------------------------------------------------------- - try : - SALOME_UNIQUE_BASE_Panel.__dict__[commande](self) - except : - SALOME_UNIQUE_BASE_Panel.SALOME_DEFI_GROUP_CREA_GROUP_MA_GROUP_MA(self) - - - - def makeValeurPage(self,page): - """ - Crée la page de saisie d'une valeur à priori quelconque, - cad qui ne sont pas à choisir dans une liste prédéfinie - Ajout d'un bouton pour selectionner à partir de Salome - """ - UNIQUE_BASE_Panel.makeValeurPage(self,page) - self.b = Button(self.frame_valeur,text='Relier selection',command=self.redistribue_selon_simp) - self.b.place(relx=0.28,rely=0.4,relwidth=0.4) - -#--------------------------------------------------------------------------------------- -# Correspondances entre les classes eficas et les classes salome_eficas -#______________________________________________________________________________________ -dict_classes_salome = { SHELLPanel : SALOME_SHELLPanel, - FONCTION_Panel : SALOME_FONCTION_Panel, - PLUSIEURS_INTO_Panel : SALOME_PLUSIEURS_INTO_Panel, - PLUSIEURS_ASSD_Panel : SALOME_PLUSIEURS_ASSD_Panel, - PLUSIEURS_BASE_Panel : SALOME_PLUSIEURS_BASE_Panel, - PLUSIEURS_BASE_OR_UNELISTE_Panel : SALOME_PLUSIEURS_BASE_OR_UNELISTE_Panel, - UNIQUE_INTO_Panel : SALOME_UNIQUE_INTO_Panel, - UNIQUE_SDCO_Panel : SALOME_UNIQUE_SDCO_Panel, - UNIQUE_ASSD_Panel : SALOME_UNIQUE_ASSD_Panel, - UNIQUE_ASSD_Panel_Reel : SALOME_UNIQUE_ASSD_Panel_Reel, - UNIQUE_COMP_Panel : SALOME_UNIQUE_COMP_Panel, - UNIQUE_BASE_Panel : SALOME_UNIQUE_BASE_Panel} - -dict_geom_numgroupe = { } -dict_geom_numface = { } diff --git a/InterfaceTK/patches.py b/InterfaceTK/patches.py deleted file mode 100644 index 0bd2fc4c..00000000 --- a/InterfaceTK/patches.py +++ /dev/null @@ -1,39 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== - -""" - Ce module contient des modifications mineures du comportement - du noyau ou de validation -""" -import string - -if __name__ == "__main__": - import Noyau.N_CR - print Noyau.N_CR.encadre_message(motif='!', -texte="""- Il faut au moins un mot-clé parmi : ('DEBUT', 'POURSUITE') -- Il faut au moins un mot-clé parmi : ('FIN',) -- Il faut qu'au moins un objet de la liste : ('DEBUT', 'POURSUITE') soit suivi d'au moins un objet de la liste : ('FIN',) -ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,yyyyyyyyyyyyyyyy -""") - - - diff --git a/InterfaceTK/plusieursassdpanel.py b/InterfaceTK/plusieursassdpanel.py deleted file mode 100644 index 3e5eb99b..00000000 --- a/InterfaceTK/plusieursassdpanel.py +++ /dev/null @@ -1,183 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -# Modules Python -import string,types,os -from Tkinter import * -import Pmw -from copy import copy,deepcopy -import traceback - -# Modules Eficas -from Editeur import Objecttreeitem -import prefs -import panels -import images -from widgets import ListeChoix -from widgets import FenetreDeSelection - -from Noyau.N_CR import justify_text -from Editeur.utils import substract_list - -# Import des panels -from plusieurspanel import PLUSIEURS_Panel - -class PLUSIEURS_ASSD_Panel(PLUSIEURS_Panel): - """ - Classe définissant le panel associé aux mots-clés qui demandent - à l'utilisateur de donner une liste de valeurs qui ne sont pas - à choisir dans une liste discrètes et qui sont de type dérivé d'ASSD - """ - def makeValeurPage(self,page): - """ - Génère la page de saisie de plusieurs noms de SD parmi un ensemble discret - de SD possibles, cad d'un type cohérent avec les types attendus par le mot-clé simple - """ - # On récupère la bulle d'aide du panneau, l'objet, l'aide, min et max (cardinalité de la liste), - # la liste des valeurs déjà affectées à l'objet courant et la liste des SD du bon type - bulle_aide=self.get_bulle_aide() - self.ajout_valeurs=None - objet_mc = self.node.item.get_definition() - aide = self.get_aide() - aide = justify_text(texte=aide) - min,max = self.node.item.GetMinMax() - l_valeurs = self.node.item.GetListeValeurs() - l_choix=self.node.item.get_sd_avant_du_bon_type() - l_choix.sort() - # remplissage du panneau - self.frame_valeurs = Frame(page) - self.frame_valeurs.place(relx=0.05,rely=0.05,relwidth=0.35,relheight=0.7) - self.frame_boutons_fleches = Frame(page) - self.frame_boutons_fleches.place(relx=0.4,rely=0.,relwidth=0.2,relheight=0.7) - self.frame_choix = Frame(page) - self.frame_choix.place(relx=0.6,rely=0.05,relwidth=0.35,relheight=0.7) - self.frame_boutons = Frame(page) - self.frame_boutons.place(relx=0.35,rely=0.87,relwidth=0.5,relheight=0.1) - liste_commandes_valeurs = (("",self.selectValeur), - ("",self.deselectValeur), - ("",self.sup_valeur_sans_into)) - liste_commandes_choix = (("",self.selectChoix), - ("",self.deselectChoix), - ("",self.add_eval_valeur_sans_into)) - self.Liste_valeurs = ListeChoix(self,self.frame_valeurs,l_valeurs,liste_commandes = liste_commandes_valeurs, - titre="Valeur(s) actuelle(s)") - self.Liste_choix = ListeChoix(self,self.frame_choix,l_choix,liste_commandes = liste_commandes_choix, - titre= "Valeurs possibles") - self.bouton_add = Button(self.frame_boutons_fleches, - image = images.get_image('arrow_left'), - command = self.add_eval_valeur_sans_into) - self.bouton_sup = Button(self.frame_boutons_fleches, - image = images.get_image('arrow_right'), - command = self.sup_valeur_sans_into) - self.bouton_accepter = Button(self.frame_boutons, - text='Valider', - command = lambda s=self,m=min,M=max : s.accepte_modifs_valeur(m,M)) - self.bouton_annuler = Button(self.frame_boutons, - text = 'Annuler', - command = self.annule_modifs_valeur) - self.bouton_add.place(relx=0.3,rely=0.35) - self.bouton_sup.place(relx=0.3,rely=0.65) - for but in (self.bouton_accepter,self.bouton_annuler): - but.pack(side='left',padx=4) - self.Liste_valeurs.affiche_liste() - if len(l_valeurs) > 0 : - liste_marque=l_valeurs[-1] - self.Liste_valeurs.surligne(liste_marque) - self.Liste_choix.affiche_liste() - for fram in (self.frame_valeurs,self.frame_boutons_fleches,self.frame_choix,self.frame_boutons): - fram.bind("",lambda e,s=self,a=bulle_aide : s.parent.appli.affiche_aide(e,a)) - fram.bind("",self.parent.appli.efface_aide) - - def add_eval_valeur_sans_into(self,valeurentree=None): - if valeurentree == None: - valeurentree = self.get_valeur() - valeur,validite=self.node.item.eval_valeur(valeurentree) - if not validite : - commentaire = "impossible d'évaluer : %s " %`valeurentree` - self.parent.appli.affiche_infos(commentaire) - return - self.add_valeur_sans_into(valeur) - - def get_bulle_aide(self): - """ - Retourne la bulle d'aide associée au panneau - """ - return """Un clic sur une valeur des deux listes la sélectionne. - - Un clic sur la flèche gauche stocke la valeur possible sélectionnée - dans la liste des valeurs que vous voulez affecter au mot-clé simple - - Un clic sur la flèche droite déstocke la valeur du mot-clé simple - sélectionnée (elle apparaît alors à nouveau comme choix possible - dans la liste des choix à droite) - - Cliquez sur 'Valider' pour affecter la liste des valeurs sélectionnées - au mot-clé simple courant - - Cliquez sur 'Annuler' pour restaurer la valeur du mot-clé simple - avant toute modification depuis le dernier 'Valider'""" - - def get_aide(self): - """ - Retourne la phrase d'aide indiquant de quel type doivent être les - valeurs que doit entrer l'utilisateur - """ - commentaire="" - mc = self.node.item.get_definition() - type = mc.type[0].__name__ - if len(mc.type)>1 : - for typ in mc.type[1:] : - type = type + ' ou '+typ.__name__ - if mc.min == mc.max: - commentaire="Une liste de "+`mc.min`+" objets de type "+type+" est attendue" - else : - commentaire="Une liste d'objets de type "+type+" est attendue (min="+`mc.min`+",max="+`mc.max`+')' - aideval=self.node.item.aide() - commentaire=commentaire +"\n"+ aideval - return commentaire - - - def sup_valeur(self,name=None): - """ - Supprime la valeur selectionnée de la liste des valeurs et la rajoute - à la liste des choix possibles - """ - liste_valeurs = self.Liste_valeurs.get_liste() - liste_valeurs.remove(self.selected_valeur) - liste_choix = self.node.item.get_definition().into - liste_choix = substract_list(liste_choix,liste_valeurs) - self.Liste_valeurs.put_liste(liste_valeurs) - self.Liste_choix.put_liste(liste_choix) - self.selected_valeur = None - - def erase_valeur(self): - pass - - def get_valeur(self): - """ - Retourne la valeur sélectionnée dans la liste des choix - """ - return self.selected_choix - - def display_valeur(self,val=None): - """ - Affiche la valeur passée en argument dans l'entry de saisie. - Par défaut affiche la valeur du mot-clé simple - """ - # Il n'y a pas d'entry pour ce type de panneau - return - - diff --git a/InterfaceTK/plusieursbasepanel.py b/InterfaceTK/plusieursbasepanel.py deleted file mode 100644 index 34af53e9..00000000 --- a/InterfaceTK/plusieursbasepanel.py +++ /dev/null @@ -1,542 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -# Modules Python -import string,types,os -from Tkinter import * -import Pmw -from copy import copy,deepcopy -import traceback - -# Modules Eficas -from Editeur import Objecttreeitem -import prefs -import panels -import images -from widgets import showinfo -from widgets import askopenfilename -from widgets import ListeChoix -from widgets import FenetreDeSelection -from widgets import FenetreDeParametre - -from Noyau.N_CR import justify_text -from Ihm.I_LASSD import LASSD -from Extensions.parametre import PARAMETRE - -from Editeur.utils import substract_list -from plusieurspanel import PLUSIEURS_Panel -from uniqueassdpanel import UNIQUE_ASSD_Panel - -import fontes -import math - -class PLUSIEURS_BASE_Panel(PLUSIEURS_Panel): - """ - Classe définissant le panel associé aux mots-clés qui demandent - à l'utilisateur de donner une liste de valeurs qui ne sont pas - à choisir dans une liste discrètes et qui sont de type de base : - entier, réel, string,... - """ - def makeValeurPage(self,page): - """ - Crée la page de saisie d'une liste de valeurs à priori quelconques, - cad qui ne sont pas à choisir dans une liste prédéfinie - """ - #print "Methode Utilisée par Salome" - # On récupère la bulle d'aide du panneau, l'objet, l'aide,min et max (cardinalité de la liste), - # et la liste des valeurs déjà affectées à l'objet courant - bulle_aide=self.get_bulle_aide() - objet_mc = self.node.item.get_definition() - aide = self.get_aide() - aide = justify_text(texte=aide) - min,max = self.node.item.GetMinMax() - l_valeurs = self.node.item.GetListeValeurs() - - # création des frames globales - self.frame1 = Frame(page,relief='groove',bd=2) - self.frame2 = Frame(page) - self.frame1.place(relx=0.,rely=0.,relwidth=1.,relheight=0.85) - self.frame2.place(relx=0.,rely=0.85,relwidth=1,relheight=0.15) - self.frame_right = Frame(self.frame1) - self.frame_right.place(relx=0.35,rely=0.,relwidth=0.65,relheight=1.) - - # création des frames internes - self.frame_valeurs = Frame(self.frame1) - self.frame_valeurs.place(relx=0.02,rely=0.05,relwidth=0.35,relheight=0.95) - self.frame_boutons_fleches = Frame(self.frame_right) - self.frame_boutons_fleches.place(relx=0.,rely=0.2,relwidth=0.2,relheight=0.5) - self.frame_choix = Frame(self.frame_right) - self.frame_choix.place(relx=0.2,rely=0.2,relwidth=0.7,relheight=0.8) - self.frame_aide = Frame(self.frame_right) - self.frame_aide.place(relx=0.1,rely=0.8,relwidth=0.8,relheight=0.2) - self.frame_boutons = Frame(self.frame2) - self.frame_boutons.place(relx=0.2,rely=0.,relwidth=1,relheight=1.) - for fram in (self.frame1,self.frame2,self.frame_right,self.frame_valeurs, - self.frame_boutons_fleches,self.frame_choix,self.frame_aide,self.frame_boutons): - fram.bind("",lambda e,s=self,a=bulle_aide : s.parent.appli.affiche_aide(e,a)) - fram.bind("",self.parent.appli.efface_aide) - - # création des objets dans les frames - liste_commandes_valeurs = (("",self.selectValeur), - ("",self.deselectValeur), - ("",self.sup_valeur_sans_into)) - self.Liste_valeurs=ListeChoix(self,self.frame_valeurs,l_valeurs,liste_commandes = liste_commandes_valeurs, - titre="Valeur(s) actuelle(s)") - - # Création de l'entry ou de la liste des SD - # PN : pour ajouter les validators - self.label = Label(self.frame_choix,text="Valeur :") - self.make_entry(frame = self.frame_choix,command = self.add_valeur_plusieurs_base) - self.label.place(relx=0.05,rely=0.2) - - # Création d'un bouton "Importer ..." et d'un bouton "Paramatres" sur le panel. - bouton_valeurs_fichier = Button(self.frame_choix, - text="Importer", - command=self.select_in_file) - bouton_valeurs_fichier.place(relx=0.28,rely=0.4,relwidth=0.6) - bouton_parametres = Button(self.frame_choix, text="Parametres", command=self.affiche_parametre) - bouton_parametres.place(relx=0.28,rely=0.6,relwidth=0.6) - self.ajout_valeurs = None - - # boutons Ajouter et Supprimer - self.bouton_add = Button(self.frame_boutons_fleches, - image = images.get_image('arrow_left'), - command = self.add_valeur_plusieurs_base) - self.bouton_sup = Button(self.frame_boutons_fleches, - image = images.get_image('arrow_right'), - command = self.sup_valeur_sans_into) - self.bouton_add.place(relx=0.3,rely=0.35) - self.bouton_sup.place(relx=0.3,rely=0.65) - # affichage de l'aide - self.frame_aide.update() - self.aide = Label(self.frame_aide, - text = aide, - justify='center', - anchor='center', - wraplength=int(self.frame_aide.winfo_width()*0.8)) - self.aide.place(relx=0.5,rely=0.5,anchor='center',relwidth=1) - self.Liste_valeurs.affiche_liste() - if len(l_valeurs) > 0 : - liste_marque=l_valeurs[-1] - self.Liste_valeurs.surligne(liste_marque) - self.selectValeur(liste_marque) - # boutons Accepter et Annuler - self.bouton_accepter = Button(self.frame_boutons, - text='Valider', - command = lambda s=self,m=min,M=max : s.accepte_modifs_valeur(m,M)) - self.bouton_annuler = Button(self.frame_boutons, - text = 'Annuler', - command = self.annule_modifs_valeur) - self.bouton_accepter.place(relx=0.2, rely=0.2,relwidth=0.25) - self.bouton_annuler.place(relx=0.5, rely=0.2,relwidth=0.25) - - def affiche_parametre(self) : - if self.node.item.get_liste_param_possible() != [ ]: - txtparam="" - for param in self.node.item.get_liste_param_possible(): - txtparam=txtparam+repr(param)+"\n" - if txtparam=="": - showerror("Aucun parametre ","Pas de parametre de ce type") - else : - try : - self.self.fenetreparam.destroy() - except: - pass - self.fenetreparam=FenetreDeParametre( self, self.node.item, self.parent.appli, txtparam) - - def valid_valeur(self): - self.add_valeur_plusieurs_base() - - def add_valeur_plusieurs_base(self,name=None): - if name != None : - valeur = name - else: - valeur,validite,commentaire=self.get_valeur() - if not validite : - self.parent.appli.affiche_infos(commentaire) - return - - atraiter=[] - if type(valeur) in (types.ListType,types.TupleType) : - indice = 0 - while (indice < len(valeur)): - v=valeur[indice] - if self.node.item.wait_complex : - if (v== 'RI' or v == 'MP'): - try : - t=tuple([v,valeur[indice+1],valeur[indice+2]]) - atraiter.append(t) - indice=indice+3 - except : - validite=0 - commentaire = "Veuillez entrer le complexe sous forme aster ou sous forme python" - self.parent.appli.affiche_infos(commentaire) - return - else : # ce n'est pas un tuple à la mode aster - atraiter.append(v) - indice = indice + 1 - else: # on n'attend pas un complexe - atraiter.append(v) - indice=indice+1 - else: - atraiter.append(valeur) - - for valeur in atraiter : - encorevalide=self.node.item.valide_item(valeur) - if encorevalide : - listecourante=self.Liste_valeurs.get_liste() - encorevalide=self.node.item.valide_liste_partielle(valeur,listecourante) - if not encorevalide : encorevalide = -1 - self.add_valeur_sans_into(valeur,encorevalide) - - def select_in_file(self): - """ Permet d'ouvrir un fichier choisi par l'utilisateur. """ - nom_fichier = askopenfilename(title="Choix fichier :") - - if not nom_fichier: - return - - try: - f = open(nom_fichier, "rb") - selection_texte = f.read() - f.close() - self.ajout_valeurs = FenetreDeSelection(self, - self.node.item, - self.parent.appli, - titre="Sélection de valeurs", - texte=selection_texte) - except: - traceback.print_exc() - showinfo("Erreur de fichier","impossible d'ouvir le fichier "+nom_fichier) - - def get_bulle_aide(self): - """ - Retourne l'aide associée au panneau courant - """ - return """Taper dans la boîte de saisie de droite la valeur que - vous voulez affecter au mot-clé simple. - - Cliquez sur la flèche gauche ou pressez pour la faire glisser - dans la liste des valeurs que vous voulez affecter au mot-clé simple - - Un clic sur une valeur de la liste la sélectionne - - Un clic sur la flèche droite ou un double-clic retire la valeur - sélectionnée de la liste - - Cliquez sur 'Valider' pour que la nouvelle valeur désirée soit affectée - au mot-clé simple - - Cliquez sur 'Annuler' pour annuler toutes les modifications faites - depuis le dernier clic sur 'Valider'""" - - def get_aide(self): - """ - Retourne la phrase d'aide indiquant de quel type de base doivent être les valeurs - que saisit l'utilisateur - """ - commentaire="" - mc = self.node.item.get_definition() - d_aides = { 'TXM' : 'chaînes de caractères', - 'R' : 'réels', - 'I' : 'entiers', - 'C' : 'complexes'} - type = mc.type[0] - if not d_aides.has_key(type) : return 'Type de base inconnu' - if mc.min == mc.max: - commentaire="Une liste de "+d_aides[type]+" de longueur " + `mc.min` + " est attendue" - else : - commentaire="Une liste de "+d_aides[type]+" est attendue (min="+`mc.min`+",max="+`mc.max`+')' - - aideval=self.node.item.aide() - commentaire=commentaire +"\n"+aideval - return commentaire - - def make_entry(self,frame,command,x=0.28,y=0.2): - self.entry = Entry(frame,relief='sunken') - self.entry.place(relx=0.28,rely=y,relwidth=0.6) - self.entry.bind("",lambda e,c=command:c()) - self.entry.bind("",lambda e,c=command:c()) - self.entry.focus() - - def get_valeur(self): - """ - Retourne la valeur saisie par l'utilisateur dans self.entry - """ - commentaire = "" - if hasattr(self,'entry'): - # Traitement d'une entree unique - valeurentree = self.entry.get() - if (valeurentree == None or valeurentree ==""): - return None,0,"" - - #On tente une evaluation globale (ne fait pas de vérification de validité - #seulement une transformation de la chaine en objet équivalent) - valeur,validite=self.node.item.eval_valeur(valeurentree) - if valeur == valeurentree: - #L'evaluation n'a rien donné : on a toujours la string - #on découpe la string sur le séparateur , si c'est possible - if valeurentree.find(',') != -1: - valeur=[] - for v in valeurentree.split(','): - vsimple,validite=self.node.item.eval_valeur(v) - valeur.append(vsimple) - - return valeur,validite,commentaire - - - # if (valeurentree[0] != "(") and (valeurentree.find(',') < len(valeurentree)): - # valeurs=[] - # for v in valeurentree.split(','): - # vsimple,validite=self.node.item.eval_valeur(v) - # Pn If ajoute pour le panneau "double" - #if isinstance(vsimple,LASSD) : - # commentaire = "impossible de mélanger reels et liste prédéfinie" - # validite = 0 - # break - # if validite : - # valeurs.append(vsimple) - # else: - # commentaire = "impossible d'évaluer : %s " %`valeurentree` - # break - # valeur=valeurs - # else: - # valeur,validite=self.node.item.eval_valeur(valeurentree) - # if not validite and commentaire == "": - # commentaire = "impossible d'évaluer : %s " %`valeurentree` - # return valeur,validite,commentaire - #else: - # # Traitement d'une entree de type complexe - # try: - # valeur= (self.typ_cplx.get(), - # string.atof(self.entry1.get()), - # string.atof(self.entry2.get())) - # return valeur,1,"" - # except: - # #traceback.print_exc() - # return None,0,"impossible d'évaluer la valeur d'entree" - - def erase_valeur(self): - """ - Efface la valeur donnée par l'utilisateur dans l'entry - """ - if hasattr(self,'entry'): - self.entry.delete(0,END) - else: - self.typ_cplx.set('RI') - self.entry1.delete(0,END) - self.entry2.delete(0,END) - - - def display_valeur(self,val=None): - """ - Affiche la valeur passée en argument dans l'entry de saisie. - Par défaut affiche la valeur du mot-clé simple - """ - if not val : - valeur = self.node.item.object.getval() - else: - valeur = val - if not valeur : return - - if hasattr(self,'entry'): - # Traitement d'une entree unique - self.entry.delete(0,END) - self.entry.insert(0,str(valeur)) - else: - # Traitement d'une entree de type complexe - typ_cplx,x1,x2=valeur - self.entry1.delete(0,END) - self.entry2.delete(0,END) - self.typ_cplx.set(typ_cplx) - self.entry1.setentry(x1) - self.entry2.setentry(x2) - -class PLUSIEURS_BASE_OR_UNELISTE_Panel(PLUSIEURS_BASE_Panel,UNIQUE_ASSD_Panel): - - def makeValeurPage(self,page): - """ - Crée la page de saisie d'une liste de valeurs à priori quelconques, - cad qui ne sont pas à choisir dans une liste prédéfinie - """ - # On récupère la bulle d'aide du panneau, l'objet, l'aide,min et max (cardinalité de la liste), - # et la liste des valeurs déjà affectées à l'objet courant - bulle_aide=self.get_bulle_aide() - objet_mc = self.node.item.get_definition() - aide = self.get_aide() - aide = justify_text(texte=aide) - aide2 = self.get_aide2() - aide2 = justify_text(texte=aide2) - min,max = self.node.item.GetMinMax() - l_valeurs = self.node.item.GetListeValeurs() - for i in l_valeurs: - if isinstance(i,LASSD) : - affiche_entry=l_valeurs - l_valeurs=() - - # Il faut traiter ici pour avoir le choix entre une liste - # deja constituee (listr8aster) ou manuelle - - # création des frames globales - self.frame1 = Frame(page,relief='groove',bd=2) - self.frame2 = Frame(page) - self.frame1.place(relx=0.,rely=0.,relwidth=1.,relheight=0.9) - self.frame2.place(relx=0.,rely=0.9,relwidth=1,relheight=0.1) - - # création des frames internes dans frame1 - self.frame_valeurs = Frame(self.frame1) - self.frame_valeurs.place(relx=0.02,rely=0.55,relwidth=0.35,relheight=0.45) - self.frame_haut = Frame(self.frame1) - self.frame_haut.place(relx=0.02,rely=0.02,relwidth=0.98,relheight=0.45) - self.frame_bas = Frame(self.frame1) - self.frame_bas.place(relx=0.37,rely=0.55,relwidth=0.63,relheight=0.45) - - # création des frames internes dans frame_right - self.frame_fleches = Frame(self.frame_bas) - self.frame_fleches.place(relx=0.,rely=0.4,relwidth=0.2,relheight=0.5) - self.frame_choix = Frame(self.frame_bas) - self.frame_choix.place(relx=0.2,rely=0.1,relwidth=0.75,relheight=1) - - # affichage de l'aide - self.aide = Label(self.frame_haut, text = aide, justify='center', anchor='center',) - self.aide.place(relx=0.72,rely=0.25,anchor='center',relwidth=1) - self.aide2 = Label(self.frame2, text = aide2,) - self.aide2.place(relx=0.4,rely=0.01,relwidth=0.6) - - # Création d'un bouton "Importer ..." et d'un bouton "Parametres" sur le panel. - bouton_valeurs_fichier = Button(self.frame_choix, - text="Importer", - command=self.select_in_file) - bouton_valeurs_fichier.place(relx=0.28,rely=0.0,relwidth=0.6) - bouton_parametres = Button(self.frame_choix, text="Parametres", command=self.affiche_parametre) - bouton_parametres.place(relx=0.28,rely=0.25,relwidth=0.6) - self.ajout_valeurs = None - - - # Création de la liste des SD - liste_noms_sd = self.node.item.get_sd_avant_du_bon_type_pour_type_de_base() - liste_noms_sd = self.tri(liste_noms_sd) - self.listbox = Pmw.ScrolledListBox(self.frame_haut, - items=liste_noms_sd, - labelpos='n', - #label_text="Structures de données du type\n requis parl'objet courant :", - label_text="Listes du type\n requis parl'objet courant :", - listbox_height = 6, - dblclickcommand=lambda s=self,c=UNIQUE_ASSD_Panel.valid_valeur : s.choose_valeur_from_list(c)) - self.listbox.place(relx=0.00,rely=0.00,relwidth=0.4) - - # On eneleve le label pour gagner de la place - #self.label = Label(self.frame_choix,text="Valeur :") - #self.label.place(relx=0.05,rely=0.85) - self.make_entry(frame = self.frame_choix,command = self.add_valeur_plusieurs_base,x=0.28,y=0.55) - - # boutons Ajouter et Supprimer - bouton_add = Button(self.frame_fleches, image = images.get_image('arrow_left'), - command = self.add_valeur_plusieurs_base) - bouton_sup = Button(self.frame_fleches, image = images.get_image('arrow_right'), - command = self.sup_valeur_sans_into) - bouton_add.place(relx=0.2,rely=0.25) - bouton_sup.place(relx=0.2,rely=0.70) - - - # boutons Accepter et Annuler dans frame2 - bouton_accepter = Button(self.frame2, text='Valider', - command = lambda s=self,m=min,M=max : s.accepte_modifs_valeur(m,M)) - bouton_annuler = Button(self.frame2, text = 'Annuler', - command = self.annule_modifs_valeur) - for but in (bouton_accepter,bouton_annuler): - but.pack(side='left',padx=5) - - # création des objets dans les frames - liste_commandes_valeurs = (("",self.selectValeur), - ("",self.deselectValeur), - ("",self.sup_valeur_sans_into)) - self.Liste_valeurs = ListeChoix(self,self.frame_valeurs,l_valeurs, - liste_commandes = liste_commandes_valeurs, - titre="Valeur(s) non-prédéfinies(s)", - fonte_titre=None - ) - - for fram in (self.frame1,self.frame2,self.frame_bas,self.frame_haut,self.frame_valeurs, - self.frame_fleches,self.frame_choix): - fram.bind("",lambda e,s=self,a=bulle_aide: s.parent.appli.affiche_aide(e,a)) - fram.bind("",self.parent.appli.efface_aide) - - self.Liste_valeurs.affiche_liste() - if len(l_valeurs) > 0 : - liste_marque=l_valeurs[-1] - self.Liste_valeurs.surligne(liste_marque) - - def get_aide(self): - """ - Retourne la phrase d'aide indiquant de quel type de base doivent être les valeurs - saisies par l'utilisateur - """ - commentaire="Ce motclef accepte soit un nom de liste déja définie soit une liste manuelle de valeurs" - return commentaire - - def get_aide2(self): - min,max = self.node.item.GetMinMax() - aideval=self.node.item.aide() - commentaire="min : " + str(min) + ", max : " + str(max) - aideval=commentaire + aideval - return aideval - - def choose_valeur_from_list(self,command): - """ - Affecte à valeur choisie la sélection courante dans la liste des choix proposés - Exécute command - """ - self.Liste_valeurs.liste=[] - self.Liste_valeurs.affiche_liste() - if len(self.listbox.get()) == 0 : return - choix = self.listbox.getcurselection()[0] - d={} - d["valeurentree"]=choix - apply(command,(self,),d) - - - - def tri(self,liste_noms_sd): - a=(3+8j) - d_types = { 'TXM' : type('A'), - 'R' : type(3.), - 'I' : type(0), - 'C' : type(a)} - - # On enleve seulement ceux qu'on peut - # Sur certaines listes, il est possible qu'on ne - # sache pas déterminer le type - listefinale=[] - typespossibles=self.node.item.object.definition.type - typecherche = None - for t in typespossibles: - if t in d_types.keys() : - typecherche = d_types[t] - break - for liste in liste_noms_sd: - valeur,validite=self.node.item.eval_valeur(liste) - for mc in valeur.etape.mc_liste : - try : - if type(mc.valeur) in (types.ListType,types.TupleType) : - typeliste=type(mc.valeur[0]) - else : - typeliste=type(mc.valeur) - if type(mc.valeur[0]) == typecherche: - listefinale.append(liste) - except: - listefinale.append(liste) - return listefinale - diff --git a/InterfaceTK/plusieursintopanel.py b/InterfaceTK/plusieursintopanel.py deleted file mode 100644 index d5ef1e15..00000000 --- a/InterfaceTK/plusieursintopanel.py +++ /dev/null @@ -1,163 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -# Modules Python -import string,types,os -from Tkinter import * -import Pmw -from copy import copy,deepcopy -import traceback - -# Modules Eficas -from Editeur import Objecttreeitem -import prefs -import panels -import images -from widgets import ListeChoix -from widgets import FenetreDeSelection - -from Noyau.N_CR import justify_text -from Editeur.utils import substract_list - -# Import des panels -from plusieurspanel import PLUSIEURS_Panel - -class PLUSIEURS_INTO_Panel(PLUSIEURS_Panel): - """ - Classe servant à définir le panneau permettant d'afficher et de saisir une - liste de valeurs à choisir parmi une liste discrètes de valeurs possibles - """ - def makeValeurPage(self,page): - """ - Génère la page de saisie de plusieurs valeurs parmi un ensemble discret - de possibles - """ - self.ajout_valeurs = None - # On récupère la bulle d'aide du panneau, l'objet, min et max (cardinalité de la liste), - # la liste des choix et la liste des valeurs - aide = self.get_aide() - aide = justify_text(texte=aide) - bulle_aide=self.get_bulle_aide() - objet_mc = self.node.item.get_definition() - min,max = self.node.item.GetMinMax() - #l_choix=list(objet_mc.into) - l_valeurs = self.node.item.GetListeValeurs() - l_choix= self.node.item.get_liste_possible(l_valeurs) - # reinitialisation de l_valeurs - l_valeurs = self.node.item.GetListeValeurs() - - # remplissage du panneau - self.frame_valeurs = Frame(page) - self.frame_valeurs.place(relx=0.05,rely=0.05,relwidth=0.35,relheight=0.7) - self.frame_boutons_fleches = Frame(page) - self.frame_boutons_fleches.place(relx=0.4,rely=0.,relwidth=0.2,relheight=0.7) - self.frame_choix = Frame(page) - self.frame_choix.place(relx=0.6,rely=0.05,relwidth=0.35,relheight=0.7) - self.frame_boutons = Frame(page) - self.frame_boutons.place(relx=0.35,rely=0.87,relwidth=1,relheight=0.1) - self.frame_aide = Frame(page) - self.frame_aide.place(relx=0.1,rely=0.75,relwidth=1,relheight=0.15) - liste_commandes_valeurs = (("",self.selectValeur), - ("",self.deselectValeur), - ("",self.sup_valeur)) - liste_commandes_choix = (("",self.selectChoix), - ("",self.deselectChoix), - ("",self.add_choix)) - self.Liste_valeurs = ListeChoix(self,self.frame_valeurs, - l_valeurs,liste_commandes = liste_commandes_valeurs, - titre="Valeur(s) actuelle(s)") - self.Liste_choix = ListeChoix(self,self.frame_choix,l_choix, - liste_commandes = liste_commandes_choix, - titre= "Valeurs possibles") - self.bouton_add = Button(self.frame_boutons_fleches, - #text="<--", - image = images.get_image('arrow_left'), - command = self.add_choix) - self.bouton_sup = Button(self.frame_boutons_fleches, - #text="-->", - image = images.get_image('arrow_right'), - command = self.sup_valeur) - self.bouton_accepter = Button(self.frame_boutons, - text='Valider', - command = lambda s=self,m=min,M=max : s.accepte_modifs_valeur(m,M)) - self.bouton_annuler = Button(self.frame_boutons, - text = 'Annuler', - command = self.annule_modifs_valeur) - self.bouton_add.place(relx=0.3,rely=0.35) - self.bouton_sup.place(relx=0.3,rely=0.65) - for but in (self.bouton_accepter,self.bouton_annuler): - but.pack(side='left',padx=3) - self.Liste_valeurs.affiche_liste() - if len(l_valeurs) > 0 : - liste_marque=l_valeurs[-1] - self.Liste_valeurs.surligne(liste_marque) - self.selectValeur(l_valeurs[-1]) - self.Liste_choix.affiche_liste() - for fram in (self.frame_valeurs,self.frame_boutons_fleches,self.frame_choix,self.frame_boutons): - fram.bind("",lambda e,s=self,a=bulle_aide : s.parent.appli.affiche_aide(e,a)) - fram.bind("",self.parent.appli.efface_aide) - self.frame_aide.update() - self.aide = Label(self.frame_aide, - text = aide, - justify='center', - anchor='center') - #wraplength=int(self.frame_aide.winfo_width()*0.8)) - self.aide.place(relx=0.3,rely=0.5,anchor='center',relwidth=1) - - def get_aide(self): - """ - Retourne la phrase d'aide indiquant de quel type de base doivent être les valeurs - que saisit l'utilisateur - """ - commentaire="" - mc = self.node.item.get_definition() - d_aides = { 'TXM' : 'chaînes de caractères', - 'R' : 'réels', - 'I' : 'entiers', - 'C' : 'complexes'} - type = mc.type[0] - if not d_aides.has_key(type) : - if mc.min == mc.max: - return str(mc.min)+" valeur(s) est(sont) attendue(s)" - else : - return "entrez entre "+str(mc.min)+" et "+str(mc.max)+" valeurs" - if mc.min == mc.max: - commentaire="Une liste de "+str(mc.min)+" "+d_aides[type]+" est attendue" - else : - commentaire="Entre "+str(mc.min)+" et "+str(mc.max)+" valeurs de type "+d_aides[type]+" sont attendues" - aideval=self.node.item.aide() - commentaire=commentaire + "\n" + aideval - return commentaire - - def get_bulle_aide(self): - """ - Retourne la bulle d'aide du panneau (affichée par clic droit) - """ - return """Un clic sur une valeur des deux listes la sélectionne. - - Un clic sur la flèche gauche stocke la valeur possible sélectionnée - dans la liste des valeurs que vous voulez affecter au mot-clé simple - - Un clic sur la flèche droite déstocke la valeur du mot-clé simple - sélectionnée (elle apparaît alors à nouveau comme choix possible - dans la liste des choix à droite) - - Cliquez sur 'Valider' pour affecter la liste des valeurs sélectionnées - au mot-clé simple courant - - Cliquez sur 'Annuler' pour restaurer la valeur du mot-clé simple - avant toute modification depuis le dernier 'Valider'""" - diff --git a/InterfaceTK/plusieurspanel.py b/InterfaceTK/plusieurspanel.py deleted file mode 100644 index 0a21907e..00000000 --- a/InterfaceTK/plusieurspanel.py +++ /dev/null @@ -1,177 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -# Modules Python -import string,types,os -from Tkinter import * -import Pmw -from copy import copy,deepcopy -import traceback - -# Modules Eficas -from Editeur import Objecttreeitem -import prefs -import panels -import images -from widgets import ListeChoix -from widgets import FenetreDeSelection - -from Noyau.N_CR import justify_text -from Editeur.utils import substract_list - -# Import des panels -from newsimppanel import newSIMPPanel - - -class PLUSIEURS_Panel(newSIMPPanel): - """ - Classe virtuelle servant de classe mère à toutes celles définissant - un panneau pour un mot-clé simple qui attend une liste de valeurs - """ - def accepte_modifs_valeur(self,min,max,liste=None): - """ - Méthode qui récupère la liste des valeurs donnée par l'utilisateur - et l'affecte au mot-clé courant. - le parametre None n'est pas rempli sauf par l appel a partir de fonctionpanel - """ - if liste==None: - l1_valeurs = self.Liste_valeurs.get_liste() - else: - l1_valeurs = liste - - #nettoyage de la liste - l_valeurs=[] - for val in l1_valeurs : - if val != '' and val != None : - l_valeurs.append(val) - - longueur = len(l_valeurs) - if longueur < min or longueur > max : - self.parent.appli.affiche_infos("Valeur refusée : nombre d'éléments incorrect dans la liste") - return - if longueur > 1: - valeur = tuple(l_valeurs) - elif longueur == 1: - valeur = l_valeurs[0] - else: - valeur = None - - self.parent.appli.affiche_infos("Valeur acceptée") - self.record_valeur(valeur) - # fermeture de la fenêtre de sélection - if self.ajout_valeurs: - self.ajout_valeurs.quit() - - def annule_modifs_valeur(self): - """ - RAZ de la liste des valeurs (annule toutes les valeurs saisies par l'utilisateur) - """ - self.node.select() - # fermeture de la fenêtre de sélection - if self.ajout_valeurs: - self.ajout_valeurs.quit() - - def add_valeur_sans_into(self,name=None,encorevalide=1): - """ - Tente d'ajouter la valeur fournie (name) à la liste courante : - - si la valeur est acceptable, elle est ajoutée dans la liste des valeurs - - sinon elle est refusée - - encorevalide peut prendre les valeurs suivantes : - - - valeur 1 si le validateur trouve l item et la liste correctes - - valeur 0 si le validateur trouve la valeur de l item incorrecte - - valeur -1 si le validateur trouve la liste incorrecte - """ - valeur = name - commentaire="Valeur incorrecte : ajout à la liste refusé" - testvalide=1 - - # Pas de traitement des valeurs nulles ( a priori clic involontaire - if (valeur == None or valeur =="") : - commentaire = "Pas de saisie des valeurs nulles" - encorevalide = -2 - testtype=0 - else : - testtype,comment = self.node.item.object.verif_type(valeur) - if not testtype : - commentaire =comment - encorevalide=-2 - - if (encorevalide ==0) : - commentaire=self.node.item.info_erreur_item() - if (encorevalide == -1) : - commentaire=self.node.item.info_erreur_liste() - # On traite le cas ou la liste n est pas valide pour un pb de cardinalite - min,max = self.node.item.GetMinMax() - if len(self.Liste_valeurs.get_liste()) >= max : - commentaire="La liste a déjà atteint le nombre maximum d'éléments,ajout refusé" - - if testvalide and (encorevalide == 1): - min,max = self.node.item.GetMinMax() - - if testtype : - liste_valeurs = self.Liste_valeurs.get_liste() - if len(liste_valeurs) >= max : - commentaire="La liste a déjà atteint le nombre maximum d'éléments,ajout refusé" - else : - if (self.Liste_valeurs.selection != None): - ligne=self.Liste_valeurs.cherche_selected_item() - liste_valeurs.insert(ligne,valeur) - else : - liste_valeurs.append(valeur) - try : - self.set_valeur_texte(str(self.entry.get())) - except : - pass - self.Liste_valeurs.put_liste(liste_valeurs) - self.erase_valeur() - commentaire="Nouvelle valeur acceptée" - else : - commentaire ="Type de la valeur incorrecte" - - self.parent.appli.affiche_infos(commentaire) - - def sup_valeur_sans_into(self,name=None): - """ - Méthode qui sert à retirer de la liste des valeurs la valeur sélectionnée - """ - try: - self.Liste_valeurs.remove_selected_item() - self.display_valeur(self.selected_valeur) - self.selected_valeur = None - except: - # la valeur sélectionnée n'est pas dans la liste - return - - def display_valeur(self,val=None): - """ - Affiche la valeur passée en argument dans l'entry de saisie. - Par défaut affiche la valeur du mot-clé simple - """ - if not val : - #valeur = self.node.item.getval() - valeur = self.node.item.object.getval() - else: - valeur = val - self.entry.delete(0,END) - if not valeur : return - self.entry.insert(0,str(valeur)) - diff --git a/InterfaceTK/readercata.py b/InterfaceTK/readercata.py deleted file mode 100644 index b4d827ed..00000000 --- a/InterfaceTK/readercata.py +++ /dev/null @@ -1,444 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -""" - Ce module sert à lire un catalogue et à construire - un objet CataItem pour Eficas. - Il s'appuie sur la classe READERCATA -""" -# Modules Python -import time -import os,sys,py_compile -import traceback -import cPickle -import Pmw -import re - -# Modules Eficas -from Editeur import analyse_catalogue -from Editeur import autre_analyse_cata -from Editeur import uiinfo -from Noyau.N_CR import CR -from widgets import showinfo,showerror -from widgets import Fenetre -import fontes - -from Editeur.utils import init_rep_cata_dev - - -class READERCATA: - - menu_defs=[ - ('Catalogue',[ - ("Rapport de validation catalogue",'visuCRCATA'), - ] - ) - ] - - button_defs=[] - - def __init__(self,appli,parent): - self.appli=appli - self.parent=parent - self.code=self.appli.code - self.appli.format_fichier.set('python') - self.version_code=self.appli.version_code - self.fic_cata=None - self.version_cata=None - self.OpenCata() - self.cataitem=None - - def OpenCata(self): - """ - Ouvre le catalogue standard du code courant, cad le catalogue présent - dans le répertoire Cata - """ - if self.appli.ihm == "TK" : - import splash - message1 = "Compilation des fichiers Eficas \n\n Veuillez patienter ..." - if self.appli.test == 0 and self.appli.ihm=="TK" : - splash._splash.configure(text = message1) - self.configure_barre(4) - - liste_cata_possibles=[] - for catalogue in self.appli.CONFIGURATION.catalogues: - if catalogue[0] == self.code : - liste_cata_possibles.append(catalogue) - - if len(liste_cata_possibles)==0: - showerror("Import du catalogue","Pas de catalogue defini pour le code %s" % self.code) - self.appli.quit() - sys.exit(1) - - if self.version_code is not None: - # La version a ete fixee - for cata in liste_cata_possibles: - if self.version_code == cata[1]: - self.fic_cata = cata[2] - self.appli.format_fichier.set(cata[3]) - elif len(liste_cata_possibles)==1: - self.fic_cata = liste_cata_possibles[0][2] - self.version_code = liste_cata_possibles[0][1] - self.appli.format_fichier.set(liste_cata_possibles[0][3]) - else: - # plusieurs catalogues sont disponibles : il faut demander à l'utilisateur - # lequel il veut utiliser ... - self.ask_choix_catalogue() - - if self.fic_cata == None : - print "Pas de catalogue pour code %s, version %s" %(self.code,self.version_code) - sys.exit(0) - - # Determinination du repertoire materiau - v_codeSansPoint=self.version_code - v_codeSansPoint=re.sub("\.","",v_codeSansPoint) - chaine="rep_mat_"+v_codeSansPoint - if hasattr(self.appli.CONFIGURATION,chaine): - a=getattr(self.appli.CONFIGURATION,chaine) - else : - try : - a=self.appli.CONFIGURATION.dRepMat[self.version_code] - except : - if self.code == "ASTER" : - print "Probleme avec le repertoire materiau" - a='.' - self.appli.CONFIGURATION.rep_mat=a - - # détermination de fic_cata_c et fic_cata_p - self.fic_cata_c = self.fic_cata + 'c' - self.fic_cata_p = os.path.splitext(self.fic_cata)[0]+'_pickled.py' - - # import du catalogue - if self.appli.test == 0 and self.appli.ihm=="TK" : - splash._splash.configure(text = "Debut import_cata: %d s" % time.clock()) - self.cata = self.import_cata(self.fic_cata) - self.update_barre() - if self.appli.test == 0 and self.appli.ihm=="TK" : - splash._splash.configure(text = "Fin import_cata: %d s" % time.clock()) - if not self.cata : - showerror("Import du catalogue","Impossible d'importer le catalogue %s" %self.fic_cata) - self.appli.quit() - sys.exit(1) - # - # analyse du catalogue (ordre des mots-clés) - # - if self.appli.test == 0 and self.appli.ihm=="TK" : - splash._splash.configure(text = "Debut Retrouve_Ordre: %d s" % time.clock()) - # Retrouve_Ordre_Cata_Standard fait une analyse textuelle du catalogue - # remplacé par Retrouve_Ordre_Cata_Standard_autre qui utilise une numerotation - # des mots clés à la création - #self.Retrouve_Ordre_Cata_Standard() - self.Retrouve_Ordre_Cata_Standard_autre() - self.update_barre() - if self.appli.test == 0 and self.appli.ihm=="TK" : - splash._splash.configure(text = "Fin Retrouve_Ordre: %d s" % time.clock()) - # - # analyse des données liées à l'IHM : UIinfo - # - uiinfo.traite_UIinfo(self.cata) - self.update_barre() - - # - # traitement des clefs documentaires - # - self.traite_clefs_documentaires() - - # chargement et analyse des catalogues développeur (le cas échéant) - # - if self.appli.CONFIGURATION.isdeveloppeur == 'OUI' : - init_rep_cata_dev(self.fic_cata,self.appli.CONFIGURATION.path_cata_dev) - fic_cata_dev = os.path.join(self.appli.CONFIGURATION.path_cata_dev,'cata_developpeur.py') - if os.path.isfile(fic_cata_dev): - # il y a bien un catalogue développeur : il faut récupérer le module_object associé ... - test = self.compile_cata(fic_cata_dev,fic_cata_dev+'c') - if not test : - showinfo("Compilation catalogue développeur", - "Erreur dans la compilation du catalogue développeur") - self.cata = (self.cata,) - else: - self.cata_dev =self.import_cata(fic_cata_dev) - #self.Retrouve_Ordre_Cata_Developpeur() - self.Retrouve_Ordre_Cata_Developpeur_autre() - self.cata = (self.cata,self.cata_dev) - else: - self.cata = (self.cata,) - else: - self.cata = (self.cata,) - titreSuite=" avec le catalogue " + os.path.basename(self.fic_cata) - titre=self.appli.titre+titreSuite - if self.appli.top: - self.appli.top.title(titre) - self.appli.titre=titre - - - def import_cata(self,cata): - """ - Réalise l'import du catalogue dont le chemin d'accès est donné par cata - """ - if self.appli.test == 0 and self.appli.ihm=="TK" : - import splash - splash._splash.configure(text = "Chargement du catalogue") - nom_cata = os.path.splitext(os.path.basename(cata))[0] - rep_cata = os.path.dirname(cata) - sys.path[:0] = [rep_cata] - try : - o=__import__(nom_cata) - return o - except Exception,e: - traceback.print_exc() - return 0 - - def Retrouve_Ordre_Cata_Standard_autre(self): - """ - Construit une structure de données dans le catalogue qui permet - à EFICAS de retrouver l'ordre des mots-clés dans le texte du catalogue. - Pour chaque entité du catlogue on crée une liste de nom ordre_mc qui - contient le nom des mots clés dans le bon ordre - """ - self.cata_ordonne_dico,self.appli.liste_simp_reel=autre_analyse_cata.analyse_catalogue(self.cata) - - def Retrouve_Ordre_Cata_Standard(self): - """ - Retrouve l'ordre des mots-clés dans le catalogue, cad : - - si ce dernier a été modifié, relance l'analyse du catalogue pour déterminer - l'ordre des mots-clés dans le catalogue - - s'il n'a pas été modifié, relie le fichier pickle - """ - time1 = os.path.getmtime(self.fic_cata) - try : - time2 = os.path.getmtime(self.fic_cata_p) - except: - time2 = 0 - if time2 > time1 : - # l'objet catalogue n'a pas été modifié depuis le dernier "pickle" - self.Get_Ordre_Cata() - else : - # le catalogue a été modifié depuis le dernier "pickle" : - # il faut retrouver l'ordre du catalogue et refaire pickle - self.Get_Ordre_Cata(mode='cata') - self.appli.affiche_infos("Catalogue standard chargé") - - def Retrouve_Ordre_Cata_Developpeur(self): - """ - Retrouve l'ordre des mots-clés dans le catalogue, cad : - - si ce dernier a été modifié, relance l'analyse du catalogue pour déterminer - l'ordre des mots-clés dans le catalogue - - s'il n'a pas été modifié, relie le fichier pickle - """ - if self.code != 'ASTER' : return - fic_cata = os.path.join(self.appli.CONFIGURATION.path_cata_dev,'cata_developpeur.py') - message="Chargement catalogue développeur présent dans :\n %s..." % self.appli.CONFIGURATION.path_cata_dev - if self.appli.test == 0 and self.appli.ihm=="TK" : - splash._splash.configure(text = message,barre='oui') - cata_dev_ordonne = analyse_cata.analyse_catalogue(self,self.fic_cata) - self.cata_dev_ordonne_cr = cata_dev_ordonne.cr - cata_dev_ordonne_dico = cata_dev_ordonne.entites - self.cata_ordonne_dico.update(cata_dev_ordonne_dico) - self.appli.affiche_infos(" catalogue(s) développeur(s) chargé(s)" ) - - def Retrouve_Ordre_Cata_Developpeur_autre(self): - """ - Retrouve l'ordre des mots-clés dans le catalogue, cad : - - si ce dernier a été modifié, relance l'analyse du catalogue pour déterminer - l'ordre des mots-clés dans le catalogue - - s'il n'a pas été modifié, relie le fichier pickle - """ - if self.code != 'ASTER' : return - message="Chargement catalogue développeur présent dans :\n %s..." % self.appli.CONFIGURATION.path_cata_dev - if self.appli.test == 0 and self.appli.ihm=="TK": - splash._splash.configure(text = message,barre='oui') - cata_dev_ordonne_dico,self.appli.liste_simp_reel=autre_analyse_cata.analyse_catalogue(self.cata) - self.cata_ordonne_dico.update(cata_dev_ordonne_dico) - self.appli.affiche_infos(" catalogue(s) développeur(s) chargé(s)" ) - - def Get_Ordre_Cata(self,mode='pickle'): - """ - Retrouve l'ordre du catalogue : - - mode='pickle ': tente de relire le fichier pickle et sinon lance l'analyse du catalogue - - mode='cata' : force l'analyse du catalogue directement sans relire le pickle - """ - if mode == 'pickle' : - try: - f = open(self.fic_cata_p) - u = cPickle.Unpickler(f) - if self.appli.test == 0 and self.appli.ihm=="TK" : - splash._splash.configure(text = "Analyse du catalogue") - self.cata_ordonne_dico = u.load() - f.close() - except : - # on peut ne pas arriver à relire le fichier pickle s'il a été altéré - # ou (le plus probable) s'il a été créé sous un autre OS - self.Get_Ordre_Cata(mode='cata') - elif mode == 'cata': - if self.appli.test == 0 and self.appli.ihm=="TK" : - splash._splash.configure(text = "Analyse du catalogue",barre='oui') - cata_ordonne = analyse_catalogue.analyse_catalogue(self,self.fic_cata) - self.cata_ordonne_cr = cata_ordonne.cr - self.cata_ordonne_dico = cata_ordonne.entites - splash._splash.configure(text = "Sauvegarde des informations sur le catalogue") - f = open(self.fic_cata_p,'w+') - p = cPickle.Pickler(f) - p.dump(self.cata_ordonne_dico) - f.close() - else : - raise Exception("Appel à un mode inconnu de Get_Ordre_Cata : %s" % mode) - return - - def ask_choix_catalogue(self): - """ - Ouvre une fenêtre de sélection du catalogue dans le cas où plusieurs - ont été définis dans Accas/editeur.ini - """ - # construction du dictionnaire et de la liste des catalogues - self.dico_catalogues = {} - defaut = None - for catalogue in self.appli.CONFIGURATION.catalogues: - if catalogue[0] == self.code : - self.dico_catalogues[catalogue[1]] = catalogue - if len(catalogue) == 5 : - if catalogue[4]=='defaut' : defaut = catalogue[1] - liste_choix = self.dico_catalogues.keys() - liste_choix.sort() - # test si plusieurs catalogues ou non - if len(liste_choix) == 0: - showerror("Aucun catalogue déclaré pour %s" %self.code) - self.appli.quit() - sys.exit(1) - elif len(liste_choix) == 1: - self.fic_cata = self.dico_catalogues[liste_choix[0]][2] - self.version_code = liste_choix[0] - return - # création d'une boîte de dialogue modale - import splash - self.fenetre_choix_cata = Pmw.Dialog(splash._splash, #avec self.parent, ne marche pas sous Windows - buttons=('OK','ANNULER'), - defaultbutton = 'OK', - title = "Choix d'une version du code %s" %self.code, - command = self.chooseCata) - # construction des radioboutons - label = `len(liste_choix)`+' versions du code %s sont disponibles\n' %self.code - label = label + 'Veuillez choisir celle avec laquelle vous souhaitez travailler :' - self.radiobutton = Pmw.RadioSelect(self.fenetre_choix_cata.interior(), - buttontype='radiobutton', - labelpos = 'w', - label_text = label, - label_font = fontes.standard, - orient='vertical') - for choix in liste_choix : - self.radiobutton.add(choix) - if defaut == None : - # aucun catalogue par défaut n'a été spécifié dans Accas/editeur.ini - defaut = liste_choix[0] - self.radiobutton.invoke(defaut) - self.radiobutton.pack(fill='x',padx=10,pady=10) - # centrage de la fenêtre - self.fenetre_choix_cata.activate(geometry='centerscreenalways') - - def chooseCata(self,txt): - """ - Méthode activée lorsque l'utilisateur a fait son choix et cliqué sur 'OK' ou sur 'ANNULER' - """ - if txt == 'OK' : - version_cata = self.radiobutton.getcurselection() - self.fic_cata = self.dico_catalogues[version_cata][2] - self.version_code = version_cata - self.appli.format_fichier.set(self.dico_catalogues[version_cata][3]) - self.fenetre_choix_cata.destroy() - else: - self.parent.destroy() - - def compile_cata(self,cata,catac): - """ - Teste si le catalogue a bien besoin d'être recompilé et si oui, le compile et - affiche un message dans le splash . Retourne 1 si la compilation s'est bien déroulée, - 0 sinon. - """ - time1 = os.path.getmtime(cata) - try: - time2 = os.path.getmtime(catac) - except: - time2 = 0 - if time1 > time2: - try: - # le catalogue doit être recompilé avant d'être importé - if self.appli.test == 0 and self.appli.ihm=="TK" : - splash._splash.configure(text="Compilation du catalogue\nCela peut prendre plusieurs secondes ...") - py_compile.compile(cata) - except: - return 0 - return 1 - - -#-------------------------------------------------------------------------------- -# Méthodes concernant la barre de progression lors de l'analyse du catalogue -#-------------------------------------------------------------------------------- - - def configure_barre(self,nbcommandes): - """ Configure la barre de progression en lui passant comme paramètre le - nombre de commandes du catalogue qui lui sert à déterminer la longueur de son incrément """ - try: - if self.appli.test == 0 and self.appli.ihm=="TK" : - splash._splash.configure(barre='oui',ratio = nbcommandes) - except: - pass - - def update_barre(self): - """ Update la position de la barre de progression : la fait progresser de son incrément """ - try: - if self.appli.test == 0 and self.appli.ihm=="TK" : - splash._splash.update_barre() - except: - pass - - def visuCRCATA(self): - """ - Méthode permettant l'affichage du rapport de validation - """ - cr = CR( debut = "Début rapport de validation du catalogue", - fin = "Fin rapport de validation du catalogue") - titre="rapport de validation du catalogue" - if hasattr(self,'cata_ordonne_cr') : - cr.add(self.cata_ordonne_cr) - if hasattr(self,'cata_dev_ordonne_cr') : - cr.add(self.cata_dev_ordonne_cr) - for cata in self.cata: - if hasattr(cata,'JdC'): - cr.add(cata.JdC.report()) - texte_cr = str(cr) - self.visu_texte_cr = Fenetre(self.appli,titre=titre,texte=texte_cr) - - - def traite_clefs_documentaires(self): - try: - self.fic_cata_clef=os.path.splitext(self.fic_cata_c)[0]+'_clefs_docu' - f=open(self.fic_cata_clef) - except: - #print "Pas de fichier associé contenant des clefs documentaires" - return - - dict_clef_docu={} - for l in f.readlines(): - clef=l.split(':')[0] - docu=l.split(':')[1] - docu=docu[0:-1] - dict_clef_docu[clef]=docu - for oper in self.cata.JdC.commandes: - if dict_clef_docu.has_key(oper.nom): - oper.docu=dict_clef_docu[oper.nom] diff --git a/InterfaceTK/shellpanel.py b/InterfaceTK/shellpanel.py deleted file mode 100644 index b7682198..00000000 --- a/InterfaceTK/shellpanel.py +++ /dev/null @@ -1,96 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -# Modules Python -import string,types,os -from Tkinter import * -import Pmw -from copy import copy,deepcopy -import traceback - -# Modules Eficas -from Editeur import Objecttreeitem -#import prefs -#import panels -#import images -#from widgets import ListeChoix -#from widgets import FenetreDeSelection - -from Noyau.N_CR import justify_text -from Editeur.utils import substract_list -from newsimppanel import newSIMPPanel - - -class SHELLPanel(newSIMPPanel): - """ - Classe Panel utilisé pour les mots-clés simples qui attendent un shell pour valeur - """ - - def makeValeurPage(self,page): - """ - Affiche la page concernant l'objet pointé par self qui attend un shell - """ - objet_mc = self.node.item.get_definition() - aide = self.gen_aide() - aide = justify_text(texte=aide) - self.frame = Frame(page) - self.frame.place(relx=0,rely=0,relwidth=1,relheight=1) - label_aide = Label(self.frame,text = aide) - label_aide.place(relx=0.5,rely=0.1,anchor='center') - self.text = Text(self.frame,bg='gray95') - self.text.place(relx=0.2,rely=0.2,relwidth=0.6,relheight=0.6) - but_val = Button(self.frame,text='Valider',command = self.valide_shell) - but_ann = Button(self.frame,text='Annuler',command = self.annule_shell) - but_val.place(relx=0.35,rely=0.9,anchor='center') - but_ann.place(relx=0.65,rely=0.9,anchor='center') - self.display_valeur() - - def gen_aide(self): - """ - Retourne une chaîne de caractères d'aide sur la valeur qu'attend l'objet - pointé par self - """ - return "Un shell est attendu" - - def valide_shell(self,event=None): - """ - Récupère la valeur saisie par l'utilisateur dans self.text - et la stocke dans l'objet MCSIMP courant - """ - texte = self.text.get(1.0,END) - self.record_valeur(texte) - - def annule_shell(self,event=None): - """ - Annule toute saisie dans self.text - """ - self.text.delete(0,END) - - def display_valeur(self,val=None): - """ - Affiche la valeur de l'objet pointé par self - """ - if val != None : - valeur = val - else: - valeur = self.node.item.get_valeur() - if valeur == None or valeur == '': return - self.text.insert(END,valeur) - diff --git a/InterfaceTK/splash.py b/InterfaceTK/splash.py deleted file mode 100644 index 2918ddfe..00000000 --- a/InterfaceTK/splash.py +++ /dev/null @@ -1,150 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -""" - Ce module permet de créer, mettre à jour et détruire - un écran Splash -""" -from Tkinter import * - -from centerwindow import centerwindow -from Tools.foztools.foztools import Slider -import fontes -import images - -_splash=None - -def init_splash(*pos,**args): - global _splash - _splash=SplashScreen(*pos,**args) - -def fini_splash(): - global _splash - _splash.quit() - _splash=None - -class SplashScreen(Toplevel): - """ - Provides a splash screen. Usage: - Subclass and override 'CreateWidgets()' - In constructor of main window/application call - - S = SplashScreen(main=self) (if caller is Toplevel) - - S = SplashScreen(main=self.master) (if caller is Frame) - - S.quit() after you are done creating your widgets etc. - """ - def __init__(self, master=None,**args): - Toplevel.__init__(self, master, relief='groove', - borderwidth=5) - self.main = master - if self.main != None : - self.main.iconify() - self.withdraw() - self.frame = Frame(self) - self.frame.pack(expand=1,fill='both') - self.init(args) - self.geometry("300x200") - self.resizable(0,0) - centerwindow(self) - self.CreateWidgets() - self.deiconify() - - def init(self,args={}): - self.text = StringVar() - self.text.set('') - self.text2 = StringVar() - self.text2.set('') - self.icone = 'logo_edf.gif' - self.barre = 'non' - if args == {} : return - if args.has_key('text'): - self.text.set(args['text']) - if args.has_key('info'): - self.text2.set(args['info']) - if args.has_key('titre'): - self.title(args['titre']) - if args.has_key('code'): - self.code = args['code'] - else: - self.code = 'inconnu' - if args.has_key('icone'): - self.icone = args['icone'] - if self.code == 'ASTER' : - self.icone = 'code_aster.gif' - elif self.code == 'SATURNE': - self.icone = 'code_saturne.gif' - elif self.code == 'DESCARTES': - self.icone = 'code_descartes.gif' - - def CreateWidgets(self): - self.catIcon = images.get_image(self.icone) - self.label = Label(self.frame, image=self.catIcon) - self.label.pack(side=TOP) - self.label = Label(self.frame, textvariable=self.text,font = fontes.standard_gras) - self.label.pack(side=TOP,expand=1,fill='both') - self.label2 = Label(self.frame, textvariable=self.text2,font = fontes.standard_italique) - self.label2.pack(side=TOP,expand=1,fill='both') - self.progress = Slider(self.frame,value=0,max=100,orientation='horizontal', - fillColor='#00008b',width=200,height=30, - background='white',labelColor='red') - centerwindow(self) - - def update_barre(self,event=None): - """ Permet de faire avancer la barre de progression """ - try: - self.progress.value = self.progress.value+self.increment - self.progress.update() - except: - pass - - def configure_barre(self): - """ - Calcule l'incrément de progression de la barre en fonction - du nombre d'opérations à effectuer afin que le compteur - soit à 100% à la fin des opérations - """ - self.increment = 100./self.ratio - self.progress.update() - - def configure(self,**args): - if args.has_key('text'): - self.text.set(args['text']) - if args.has_key('info'): - self.text2.set(args['info']) - if args.has_key('titre'): - self.title(args['titre']) - if args.has_key('barre'): - old = self.barre - self.barre = args['barre'] - if self.barre == 'oui' and old == 'non': - self.progress.frame.pack(in_=self.frame,side='top') - elif self.barre == 'non' and old == 'oui': - self.progress.frame.pack_forget() - if args.has_key('ratio'): - self.ratio = args['ratio'] - self.configure_barre() - self.update() - - def quit(self): - self.progress = None - self.destroy() - if self.main: - centerwindow(self.main,parent='sans') - self.main.deiconify() - diff --git a/InterfaceTK/statusbar.py b/InterfaceTK/statusbar.py deleted file mode 100644 index e3b809b8..00000000 --- a/InterfaceTK/statusbar.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -""" -""" -# Modules Python -import Tkinter -import types - -class STATUSBAR: - def __init__(self,parent,police): - self.parent=parent - self.police=police - self.frame = Tkinter.Frame(parent,bd=1, relief=Tkinter.RAISED) - self.frame.pack(side=Tkinter.BOTTOM, fill=Tkinter.X) - self.label = Tkinter.Label (self.frame, - fg='black', - text='', - justify='left', - relief='sunken', - height=3, - bg='gray95') - self.label.pack(side='left',expand=1,fill='both') - - def affiche_infos(self,texte): - if len(texte)>150 : - texte_infos=texte[0:150] - else : - texte_infos=texte - self.label.configure(text=texte_infos,font=self.police) - - def reset_affichage_infos(self): - """ Efface tout message présent dans le panneau en bas d'EFICAS """ - self.affiche_infos('') - diff --git a/InterfaceTK/styles.py b/InterfaceTK/styles.py deleted file mode 100644 index 2d5fc4a2..00000000 --- a/InterfaceTK/styles.py +++ /dev/null @@ -1,21 +0,0 @@ -# -*- coding: utf-8 -*- -import os -import prefs -import basestyle -from basestyle import STYLE,style - -inistylefile=os.path.join(prefs.REPINI,"style.py") -if os.path.isfile(inistylefile): - execfile(inistylefile) - -userstylefile=os.path.expanduser("~/Eficas_install/style.py") -if os.path.isfile(userstylefile): - execfile(userstylefile) - -import fontes -for attr in dir(style): - if attr[0]=='_':continue - if not hasattr(fontes,attr):continue - setattr(fontes,attr,getattr(style,attr)) - - diff --git a/InterfaceTK/toolbar.py b/InterfaceTK/toolbar.py deleted file mode 100644 index 74248a09..00000000 --- a/InterfaceTK/toolbar.py +++ /dev/null @@ -1,145 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -""" -""" -# Modules Python -import string -from Tkinter import * -import Pmw - -# Modules Eficas -import images - -class TOOLBAR: - def __init__(self,appli,parent): - # parent représente l'objet graphique parent - self.parent=parent - # appli représente l'objet application parent - self.appli=appli - self.balloon = None - self.l_boutons_a_activer = [] - self.barreboutons=Frame(self.parent,relief='ridge',bd=2) - self.barreboutons.pack(anchor='nw',expand=0,fill=X) - # bouton Infos à l'extrême droite de la barre des boutons - b = Button(self.barreboutons, - image = images.get_image('About24'), - command = self.view_infos) - b.pack(side='right') - texte = "Infos EFICAS" - b.bind("",lambda e,s=self,but=b,t=texte : s.affiche_balloon(e,but,t,pos='right')) - b.bind("", self.efface_balloon) - - def appelle_commande(self,e,b,c): - try : - c() - except : - pass - - def inactive_boutons(self): - """ - Inactive les boutons de la liste self.l_boutons_a_activer - --> cette méthode est appelée dès qu'il n'y a pas de JDC courant - """ - for but in self.l_boutons_a_activer: - but.configure(state='disabled') - - def active_boutons(self): - """ - Active les boutons de la liste self.l_boutons_a_activer - --> cette méthode est appelée dès qu'il y a un JDC courant - """ - for but in self.l_boutons_a_activer: - but.configure(state='normal') - - def affiche_balloon(self,event,bouton,bulle,pos='left'): - """ - Affiche le balloon bulle associé au bouton bouton - """ - etat = bouton.cget('state') - if etat != 'normal' : return - geom = bouton.winfo_geometry() - l_args = string.split(geom,'+') - x = eval(l_args[1])+event.x+10 - self.balloon = Label(self.parent, - text = bulle, - background="yellow", - borderwidth=2, - relief='ridge') - if pos == 'left': - self.balloon.place(in_=self.parent,x=x,y=32) - else: - self.balloon.place(in_=self.parent,x=x,y=32,anchor='ne') - - def efface_balloon(self,event=None): - """ - Efface le balloon courant - """ - if self.balloon : - self.balloon.destroy() - self.balloon = None - - def view_infos(self): - """ - Permet d'afficher des infos sur la session courante d'EFICAS - """ - self.fen_infos = Pmw.Dialog(self.parent, - title = 'Informations session EFICAS', - buttons = ('Fermer',), - command = self.close_infos) - self.fen_infos.withdraw() - texte_infos = self.appli.get_texte_infos() - Label(self.fen_infos.interior(), - text = texte_infos, - anchor='center').pack(side='top',anchor='center') - self.fen_infos.activate(geometry = 'centerscreenalways') - - def close_infos(self,lbl): - """ - Ferme la fenêtre des infos - """ - self.fen_infos.destroy() - - def creer_boutons_appli_composant(self,l_boutons,appli_composant): - for bouton in l_boutons : - if not bouton : - # on veut afficher un bouton vide (=espace entre boutons) - Button(self.barreboutons, - image = images.get_image('Sep'), - state='disabled', - relief = 'flat').pack(side='left') - continue - nom_fic,commande,texte,statut = bouton - commande=getattr(appli_composant,commande) - b = Button(self.barreboutons, - image = images.get_image(nom_fic), - command = commande, - relief='flat') - b.pack(side='left') - b.bind("",lambda e,s=self,but=b,t=texte : s.affiche_balloon(e,but,t)) - b.bind("", self.efface_balloon) - b.bind("", lambda e,s=self,but=b,c=commande:s.appelle_commande(e,but,c)) - if statut != 'always': - self.l_boutons_a_activer.append(b) - - # inactive les boutons qui doivent l'être tant qu'aucun JDC courant - self.inactive_boutons() - - diff --git a/InterfaceTK/tooltip.py b/InterfaceTK/tooltip.py deleted file mode 100644 index 18fbabb5..00000000 --- a/InterfaceTK/tooltip.py +++ /dev/null @@ -1,127 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -""" - Ce module propose la classe TOOLTIP pour - mettre en oeuvre les bulles d'aide -""" - -import Tkinter -import types - -def destruct(obj): - # assist in breaking circular references - if obj is not None: - assert type(obj) is types.InstanceType - for k in obj.__dict__.keys(): - obj.__dict__[k] = None - ##del obj.__dict__[k] - -def after(widget, ms, func, *args): - timer = apply(widget.after, (ms, func) + args) - command = widget._tclCommands[-1] - return (timer, command, widget) - -def after_cancel(t): - if t is not None: - t[2].after_cancel(t[0]) - try: - t[2].deletecommand(t[1]) - except Tkinter.TclError: - pass - -class TOOLTIP: - def __init__(self,widget,text=None): - self.widget=widget - self.text = text - self.timer = None - self.tooltip = None - self.label = None - self.bindings = [] - self.bindings.append(self.widget.bind("", self._enter)) - self.bindings.append(self.widget.bind("", self._leave)) - self.bindings.append(self.widget.bind("", self._leave)) - # user overrideable settings - self.time = 1000 # milliseconds - self.relief = Tkinter.SOLID - self.justify = Tkinter.LEFT - self.fg = "#000000" - self.bg = "#ffffe0" - self.xoffset = 20 - self.yoffset = 1 - - def setText(self, text): - self.text = text - - def _unbind(self): - if self.bindings and self.widget: - self.widget.unbind("", self.bindings[0]) - self.widget.unbind("", self.bindings[1]) - self.widget.unbind("", self.bindings[2]) - self.bindings = [] - - def destroy(self): - self._unbind() - self._leave() - - def _enter(self, *event): - after_cancel(self.timer) - self.timer = after(self.widget, self.time, self._showTip) - - def _leave(self, *event): - after_cancel(self.timer) - self.timer = None - if self.tooltip: - self.label.destroy() - destruct(self.label) - self.label = None - self.tooltip.destroy() - destruct(self.tooltip) - self.tooltip = None - - def _showTip(self): - if self.tooltip or not self.text: - return - c = self.widget.__class__ - if c in (Tkinter.Button,): - if self.widget["state"] == Tkinter.DISABLED: - return - x = self.widget.winfo_rootx() - y = self.widget.winfo_rooty() + self.widget.winfo_height() - x = x + self.xoffset - y = y + self.yoffset - self.tooltip = Tkinter.Toplevel() - self.tooltip.wm_iconify() - self.tooltip.wm_overrideredirect(1) - self.tooltip.wm_protocol("WM_DELETE_WINDOW", self.destroy) - self.label = Tkinter.Label(self.tooltip, text=self.text, - relief=self.relief, justify=self.justify, - fg=self.fg, bg=self.bg, bd=1, takefocus=0) - self.label.pack(ipadx=1, ipady=1) - self.tooltip.wm_geometry("%+d%+d" % (x, y)) - self.tooltip.wm_deiconify() - -if __name__ == "__main__": - root=Tkinter.Tk() - label = Tkinter.Label(root, text="coucou") - label.pack() - tp=TOOLTIP(label,"texte d'aide") - root.mainloop() - diff --git a/InterfaceTK/treeitemincanvas.py b/InterfaceTK/treeitemincanvas.py deleted file mode 100644 index db38e98f..00000000 --- a/InterfaceTK/treeitemincanvas.py +++ /dev/null @@ -1,73 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -""" -""" -# Modules Python -import Tkinter,Pmw - -# Modules Eficas -from Editeur import Objecttreeitem -import treewidget -Objecttreeitem.TreeItem.itemNode=treewidget.Node - -class TREEITEMINCANVAS: - def __init__(self,object,nom="",parent=None,appli=None,sel=None,rmenu=None): - self.object=object - self.nom=nom - - if not appli: - class Appli: - def affiche_infos(self,message): - pass - appli=Appli() - self.appli=appli - - if not parent: - parent=Tkinter.Tk() - Pmw.initialise(parent) - self.parent=parent - - self.item=Objecttreeitem.make_objecttreeitem(self.appli,self.nom,self.object) - self.canvas=Pmw.ScrolledCanvas(self.parent,borderframe=1,canvas_background='gray95') - self.canvas.pack(padx=10,pady=10,fill = 'both', expand = 1) - if not sel: - def sel(event=None): - return - self.tree=treewidget.Tree(self.appli,self.item,self.canvas,command=sel,rmenu=rmenu) - self.tree.draw() - - def mainloop(self): - self.parent.mainloop() - - def update(self): - """Cette methode est utilisee pour signaler une mise a jour des objets associes""" - self.tree.update() - - def supprime(self): - #print "supprime",self - self.tree.supprime() - self.tree=None - self.canvas.destroy() - self.canvas=None - - #def __del__(self): - # print "__del__",self - diff --git a/InterfaceTK/treewidget.py b/InterfaceTK/treewidget.py deleted file mode 100644 index 830108c7..00000000 --- a/InterfaceTK/treewidget.py +++ /dev/null @@ -1,948 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -import os,sys,string,re,types,traceback -from Tkinter import * - - -import fontes -import images -from Ihm import CONNECTOR - -# -__version__="$Name: $" -__Id__="$Id: treewidget.py,v 1.1.4.3 2007-11-16 08:56:03 cchris Exp $" -# - -Fonte_Standard = fontes.standard - -class Tree : - def __init__(self,appli,jdc_item,scrolledcanvas,command = None,rmenu=None): - self.item = jdc_item - self.scrolledcanvas = scrolledcanvas - self.canvas = self.scrolledcanvas.component('canvas') - #resolution - resolution= self.canvas.winfo_screenwidth()/(self.canvas.winfo_screenmmwidth()/25.4*72) - self.DDY=max(20,resolution*(Fonte_Standard[1]+4)) - self.id_up=self.canvas.bind("", self.page_up) - self.id_down=self.canvas.bind("", self.page_down) - self.id_um=self.canvas.bind("", self.mot_up) - self.id_dm=self.canvas.bind("", self.mot_down) - self.id_s=self.canvas.bind("<1>", self.canvas_select) - self.tree = self - self.command = command - self.rmenu=rmenu - self.appli = appli - self.parent = None - self.racine = self - self.node_selected = None - self.build_children() - - def canvas_select(self,event): - self.canvas.focus_set() - - def page_up(self,event): - event.widget.yview_scroll(-1, "page") - - def page_down(self,event): - event.widget.yview_scroll(1, "page") - - def unit_up(self,event): - event.widget.yview_scroll(-1, "unit") - - def unit_down(self,event): - event.widget.yview_scroll(1, "unit") - - def mot_down(self,event): - self.select_next(None) - self.canvas.focus_set() - - def mot_down_force(self): - self.select_next(None) - self.canvas.focus_set() - - def mot_up(self,event): - self.node_selected.select_mot_previous() - self.canvas.focus_set() - - def mot_up_force(self): - self.node_selected.select_mot_prev() - self.canvas.focus_set() - - def deplieReplieNode(self): - self.node_selected.deplieReplieNode() - - def build_children(self): - """ Construit la liste des enfants de self """ - self.children = [] - child = self.item.itemNode(self,self.item,self.command,self.rmenu) - self.children.append(child) - child.state='expanded' - - def draw(self): - """ Dessine l'arbre """ - lasty = 8 - x = 5 - for child in self.children: - child.draw(x,lasty) - lasty = child.lasty + 15 - self.children[0].select() - self.resizescrollregion() - - def deselectall(self): - """ déselectionne tous les éléments de l'arbre """ - if self.node_selected : - self.node_selected.deselect() - - def update(self): - """ Update tous les éléments de l'arbre """ - for child in self.children: - child.update() - - def supprime(self): - """ supprime tous les éléments de l'arbre """ - #print "supprime",self - self.canvas.unbind("",self.id_up) - self.canvas.unbind("",self.id_down) - self.canvas.unbind("",self.id_um) - self.canvas.unbind("",self.id_dm) - self.canvas.unbind("<1>",self.id_s) - self.tree = None - self.racine = None - self.node_selected = None - self.item = None - self.scrolledcanvas = None - self.canvas = None - self.command = None - self.rmenu=None - for child in self.children: - child.supprime() - self.children=[] - - def update_valid(self) : - """Cette methode a pour but de mettre a jour la validite du noeud - et de propager la demande de mise à jour à son parent - """ - pass - - def resizescrollregion(self): - x0,y0,x1,y1=self.canvas.bbox(ALL) - # On ajoute une marge approximativement de la moitié du canvas - y1=y1+self.canvas.winfo_height()/2 - self.canvas.configure(scrollregion = (x0,y0,x1,y1)) - - def select_next(self,event): - self.node_selected.select_next() - self.canvas.focus_set() - - def select_previous(self,event): - self.node_selected.select_previous() - - def see(self,items): - x1, y1, x2, y2=apply(self.canvas.bbox, items) - while x2 > self.canvas.canvasx(0)+self.canvas.winfo_width(): - old=self.canvas.canvasx(0) - self.canvas.xview_scroll( 1, 'units') - # avoid endless loop if we can't scroll - if old == self.canvas.canvasx(0): - break - while y2 > self.canvas.canvasy(0)+self.canvas.winfo_height(): - old=self.canvas.canvasy(0) - self.canvas.yview_scroll( 1, 'units') - if old == self.canvas.canvasy(0): - break - # done in this order to ensure upper-left of object is visible - while x1 < self.canvas.canvasx(0): - old=self.canvas.canvasx(0) - self.canvas.xview_scroll( -1, 'units') - if old == self.canvas.canvasx(0): - break - while y1 < self.canvas.canvasy(0): - old=self.canvas.canvasy(0) - self.canvas.yview_scroll( -1, 'units') - if old == self.canvas.canvasy(0): - break - - #def __del__(self): - # print "__del__",self - - -class Node : - def __init__(self,parent,item,command=None,rmenu=None): - self.parent = parent - self.item = item - self.connect() - self.command = command - self.rmenu=rmenu - self.tree = self.parent.tree - self.appli = self.parent.appli - self.canvas = self.parent.canvas - self.init() - - def init(self): - self.state='collapsed' - self.displayed = 0 - self.selected = 0 - self.x = self.y =None - self.lasty = 0 - self.children = None - self.id = [] - if self.parent is self.tree: - self.racine=self - else: - self.racine = self.parent.racine - - def connect(self): - self.item.connect("add",self.onAdd,()) - self.item.connect("supp",self.onSupp,()) - self.item.connect("valid",self.onValid,()) - - #def __del__(self): - # print "__del__",self - - def force_select(self): - if self.selected: - # le noeud est selectionné. On force la reconstruction du panel associé - if self.command:apply(self.command,(None,)) - self.select() - - def onValid(self): - #print "onValid : l'item a changé de validité ",self.item,self.item.object,self.item.object.isvalid() - self.update_node_valid() - self.update_node_label() - self.update_node_texte() - if self.selected and self.command: - self.command(self) - - def onAdd(self,objet): - #print "onAdd : un objet a été ajouté aux fils de l'item ",self.item.object,objet - self.expand_node() - old_nodes=self.children - self.update_nodes() - self.redraw_children(old_nodes) - self.force_select() - - def onSupp(self,objet): - #print "onSupp : un objet a été supprimé des fils de l'item ",self.item.object,objet - self.expand_node() - old_nodes=self.children - self.update_nodes() - self.redraw_children(old_nodes) - self.force_select() - - def update_nodes(self): - #print "update_nodes",self - newnodes=[] - inodes=iter(self.children) - sublist=self.item._GetSubList() - iliste=iter(sublist) - - while(1): - old_item=item=None - for node in inodes: - old_item=node.item - if old_item in sublist:break - #print "item supprime",old_item - for item in iliste: - if item is old_item:break - #print "item ajoute",item - child = item.itemNode(self,item,self.command,self.rmenu) - newnodes.append(child) - - if old_item is None and item is None:break - if old_item is item: - #print "item conserve",item - newnodes.append(node) - - self.children=newnodes - self.connect() - - def supprime(self): - #print "supprime",self - self.efface_node() - self.racine = None - self.command = None - self.rmenu=None - if not self.children : return - for child in self.children: - child.supprime() - self.children=None - - def redraw_children(self,old_nodes): - #print "redraw_children",old_nodes - #print self.children - y = self.y + self.tree.DDY - x = self.x + 15 - supp_nodes=[] - - inodes=iter(old_nodes) - iliste=iter(self.children) - # on parcourt la liste des anciens noeuds (node) - # et la liste des nouveaux noeuds (new_node) en parallele (iterateurs) - - while(1): - new_node=node=None - for node in inodes: - #print "ancien noeud",node - if node in self.children:break # ancien noeud toujours present - #print "noeud supprime",node,node.item.GetLabelText()[0] - dy=node.y-node.lasty -self.tree.DDY - #print "deplacer noeuds",y,dy - node.move_nodes(y,dy) - node.supprime() - #supp_nodes.append(node) - - for new_node in iliste: - #print "nouveau noeud",new_node - if new_node in old_nodes: break # nouveau noeud deja present - #print "noeud ajoute",new_node,new_node.item.GetLabelText()[0] - y=self.draw_node(new_node,x,y) - - if node is None and new_node is None : break - - if node is new_node: # ancien noeud - #print "noeud conserve",node - node.update_node_label() - y=y+node.lasty-node.y +self.tree.DDY - - self.racine.update_coords() - self.canvas.delete('line') - self.racine.trace_ligne() - self.tree.resizescrollregion() - # Mettre à 1 pour verifier les cycles entre objets node - #withCyclops=0 - #if withCyclops: - #from Misc import Cyclops - #z = Cyclops.CycleFinder() - #print supp_nodes - #for o in supp_nodes: - #z.register(o) - #del supp_nodes - #del o - #z.find_cycles() - #z.show_stats() - #z.show_cycles() - - def tag_move_nodes(self,y): - """ Marque pour deplacement tous les noeuds au dela de l'ordonnée y """ - #print "tag_move_nodes",y - self.canvas.dtag(ALL,'move') - # on marque tous les ids au dela de y - x0, y0, x1, y1 = self.canvas.bbox(ALL) - if y > y1: # pas d'objet a deplacer - return - self.canvas.addtag_overlapping('move',x0,y,x1,y1) - - def move_nodes(self,y,dy): - """ Déplace de l'incrément dy les noeuds au dela de l'ordonnée y """ - #print "move_nodes",y,dy - self.tag_move_nodes(y) - # on déplace tous les items de dy - self.canvas.move('move',0,dy) - - def draw_node(self,new_node,x,y): - """ Dessine le noeud new_node en x,y en deplacant les noeuds existants - en y et au dela - Retourne la position du premier des noeuds deplaces - """ - #print "draw_node",new_node,x,y - self.tag_move_nodes(y) - #if new_node.item.isactif(): - #new_node.state = 'expanded' - new_node.state = 'expanded' - new_node.draw(x,y) - dy=(new_node.get_nb_children()+1)*self.tree.DDY - #print "deplacer noeuds",y,dy - self.canvas.move('move',0,dy) - return new_node.lasty+self.tree.DDY - - def build_children(self): - """ Construit la liste des enfants de self """ - self.children = [] - sublist = self.item._GetSubList() - if not sublist : return - for item in sublist : - child = item.itemNode(self,item,self.command,self.rmenu) - self.children.append(child) - - #----------------------------------------------- - # Méthodes de sélection/déselection d'un noeud - #----------------------------------------------- - - def select(self, event=None): - """ - Rend le noeud courant (self) sélectionné et déselectionne - tous les autres - """ - #print "SELECT",self - if not self.children : self.build_children() - self.tree.deselectall() - self.selected = 1 - self.tree.node_selected = self - if self.command:apply(self.command,(self,)) - self.highlight() - self.make_visible() - - def deselect(self, event=None): - """ Déselectionne self """ - self.selected = 0 - if self.displayed == 1 : self.dehighlight() - - def make_visible(self): - """ Rend l'objet self visible cad déplace le scroll pour que self - soit dans la fenêtre de visu - """ - lchild=self.last_child() - self.tree.see((self.image_id,lchild.image_id)) - - def select_next(self,ind=0): - """ on doit chercher à sélectionner dans l'ordre: - - son premier fils s'il est affiché - - son frère cadet s'il existe - - son oncle (benjamin de son père) - - ... appel récursif ... - """ - if self.state=='expanded' and len(self.children) > ind: - self.children[ind].select() - else : - index = self.parent.children.index(self) + 1 - try : - if isinstance(self.parent,TREE) : - try: - self.children[ind].select() - except: - self.children[0].select() - except : - if self.parent is self.tree: - pass - else : - self.parent.select_next(index) - - def select_mot_prev(self): - index = self.parent.children.index(self) - 1 - try : - if index > -1 : - self.parent.children[index].select() - if self.parent.children[index].state=="expanded": - print len(self.parent.children[index].children) - if len(self.parent.children[index].children)!=0 : - max=len(self.parent.children[index].children) - 1 - self.parent.children[index].children[max].select() - else : - self.parent.children[index].select() - else : - self.parent.children[index].select() - elif self.parent is self.tree: - pass - else : - self.parent.select() - except: - if self.parent is self.tree: - pass - else : - self.parent.select_previous() - - - def select_mot_previous(self): - index = self.parent.children.index(self) - 1 - try : - if index > -1 : - self.parent.children[index].select() - elif self.parent is self.tree: - pass - else : - self.parent.select() - except: - if self.parent is self.tree: - pass - else : - self.parent.select_previous() - - def select_previous(self): - """ on doit d'abord sélectionner(dans l'ordre) : - - son frère aîné - - son père - """ - index = self.parent.children.index(self) - 1 - try : - self.parent.children[index].select() - except: - #self.parent.select() - if self.parent is self.tree: - pass - else : - self.parent.select_previous() - - def popup(self,event=None): - """ - Declenche le traitement associé au clic droit de la souris - sur l'icone du Node - """ - if not self.rmenu:return - apply(self.rmenu,(self,event)) - - #----------------------------------------------- - # Méthodes de recherche d'informations - #----------------------------------------------- - def geticonimage(self,name=None): - """ - Retourne l'image qui doit être associée à self - """ - if not name : - name = self.item.GetIconName() - if not name or name == 'aucune' : - return None - return images.get_image(name) - - def get_nb_children(self): - """ Retourne le nombre d'enfants affichés de self """ - nb = 0 - if self.state =='collapsed' : return nb - for child in self.children : - nb = nb + 1 + child.get_nb_children() - return nb - - def get_liste_id(self): - """ Retourne la liste de tous les id (filiation comprise) de self """ - liste = self.id - for child in self.children: - liste.extend(child.get_liste_id()) - return liste - - def get_node_fils(self,name) : - """ Retourne le fils de self de nom name s'il existe""" - for child in self.children: - if child.item.get_nom() == name: return child - return None - - #----------------------------------------------- - # Méthodes d'affichage d'un noeud - #----------------------------------------------- - def draw(self,x,y): - """ Permet de tracer le noeud self """ - # le début du noeud est en x,y - self.x = x - self.y = y - self.lasty = y - self.displayed = 1 - self.id=[] - # choix de l'icone à afficher : + ou - - if self.item.IsExpandable(): - if self.state == 'expanded': - iconname = "minusnode" - callback = self.collapse - else: - iconname = "plusnode" - callback = self.expand - image = self.geticonimage(name=iconname) - self.icone_id = self.canvas.create_image(self.x, self.y, image=image) - self.callback_id=self.canvas.tag_bind(self.icone_id, "<1>", callback) - self.id.append(self.icone_id) - # création de la ligne horizontale - self.ligne_id = self.canvas.create_line(self.x,self.y,self.x+10,self.y) - self.id.append(self.ligne_id) - self.canvas.tag_lower(self.ligne_id) - # affichage de l'icone (carre ,rond, ovale ...) de couleur - image = self.geticonimage() - if image != None : - self.image_id = self.canvas.create_image(self.x+15,self.y,image = image) - self.select_id2=self.canvas.tag_bind(self.image_id,"<1>",self.select) - self.popup_id2=self.canvas.tag_bind(self.image_id,"<3>",self.popup) - self.id.append(self.image_id) - else: - self.image_id = None - # affichage du texte : nom de l'objet (ETAPE ou MOT-CLE) et sa valeur - self.drawtext() - if self.state == 'expanded' : - if not self.children : self.build_children() - if len(self.children) > 0: - self.drawchildren() - self.lasty = self.children[-1].lasty - - def drawchildren(self): - """ Dessine les enfants de self """ - y = self.y + self.tree.DDY - x = self.x + 15 - for child in self.children: - child.draw(x,y) - nb = child.get_nb_children() - y = y + self.tree.DDY*(nb+1) - self.trace_ligne() - - def drawtext(self): - """ Affiche les deux zones de texte après l'icône de couleur de l'objet """ - if self.image_id != None : - textx = self.x + 30 - else: - textx = self.x + 15 - texty = self.y - # nom,fonte et couleur de l'objet du noeud à afficher - labeltext,fonte,couleur = self.item.GetLabelText() - if labeltext == '' : labeltext = ' ' - if fonte == None : fonte = Fonte_Standard - if couleur == None : couleur = 'black' - # création du widget label - self.label = Label(self.canvas, - text = labeltext, - fg = couleur, - bg = 'gray95', - font=fonte) - self.label_id = self.canvas.create_window(textx,texty,window=self.label,anchor='w') - self.id.append(self.label_id) - # bindings sur le widget label - self.select_id=self.label.bind("<1>", self.select) - self.popup_id=self.label.bind("<3>", self.popup) - self.enter_id=self.label.bind("",self.enter) - self.leave_id=self.label.bind("",self.leave) - # valeur de cet objet à afficher - x0, y0, x1, y1 = self.canvas.bbox(self.label_id) - textx = max(x1, 200) + 10 - text = self.item.GetText() or " " - self.text = Label(self.canvas, text=text, - bd=0, padx=2, pady=2,background='gray95', - font=fonte) - if self.selected: - self.highlight() - else: - self.dehighlight() - self.text_id = self.canvas.create_window(textx, texty,anchor="w", window=self.text) - self.id.append(self.text_id) - - def highlight(self,event=None): - """ Met en surbrillance self""" - if hasattr(self,'label'): - self.label.configure(fg='white',bg='#00008b') - if hasattr(self.item,'get_nom') and self.appli.salome : - if self.item.get_nom() == "AFFE_CARA_ELEM": - self.item.rmenu_specs=[("View3D", "visu_3D")] - self.tree.rmenu - - - def dehighlight(self,event=None): - """ Rétablit l'affichage normal de self""" - if hasattr(self,'label'): - self.label.configure(fg='black',bg='gray95') - - def enter(self,event=None): - """ Met en surbrillance self et affiche le fr de l'objet """ - self.highlight() - fr = self.item.get_fr() - self.appli.affiche_infos(fr) - - def leave(self,event=None): - """ Rétablit l'affichage normal de self et efface le fr de l'objet """ - if not self.selected : - self.dehighlight() - self.appli.affiche_infos('') - - def collapse_children(self): - """ Collapse récursivement tous les descendants de self """ - if not self.children : return - for child in self.children: - child.state='collapsed' - child.collapse_children() - - def deplieReplieNode(self): - if self.state == 'expanded': - self.collapse() - else : - self.expand_node() - - def collapse(self,event = None): - """ Collapse self et descendants et retrace self """ - nb = self.get_nb_children() - self.state = 'collapsed' - self.collapse_children() - self.redraw(-nb) - self.select() - - def expand_node(self,event = None): - """ Expanse self et le retrace """ - if self.state == 'expanded':return - #if not self.item.isactif() : return - if not self.children : self.build_children() - self.state = 'expanded' - nb = self.get_nb_children() - self.redraw(nb) - - def expand(self,event = None): - """ Expanse self et le retrace """ - self.expand_node() - self.select() - - def redraw(self,nb): - """ Redessine self : nb est le décalage à introduire - en dessous de self pour le redessiner """ - # nb = nombre d'items de décalage - self.move(self.tree.DDY*nb) - # on efface self et on le redessine - self.efface() - self.draw(self.x,self.y) - # Il n'est pas nécessaire d'appeler update - # il suffit d'updater les coordonnees et de retracer les lignes - self.racine.update_coords() - self.racine.trace_ligne() - self.update_valid() - self.tree.resizescrollregion() - - def update_coords(self): - """ Permet d'updater les coordonnes de self et de tous ses enfants""" - if self.displayed == 0 : return - if self.image_id != None : - coords = self.canvas.coords(self.image_id) - self.x = coords[0]-15 - else: - coords = self.canvas.coords(self.label_id) - self.x = coords[0]-15 - self.y = coords[1] - self.lasty = self.y - if self.state == 'expanded' : - for child in self.children: - if child.displayed != 0: - child.update_coords() - self.lasty = child.lasty - - def update_icone(self): - """ Met à jour les icônes de tous les noeuds : teste la validité de l'objet - Cette méthode est très lente, trop !!""" - if self.image_id != None : - image = self.geticonimage() - self.canvas.itemconfig(self.image_id,image=image) - if self.state == 'expanded': - for child in self.children: - if child.displayed != 0: - child.update_icone() - - def update_label_texte(self): - """ Met a jour le label du noeud et celui de tous ses fils ouverts """ - self.update_node_label() - if self.state == 'expanded' : - for child in self.children: - if child.displayed != 0 : child.update_label_texte() - - def update_texte(self): - """ Met à jour les noms des SD et valeurs des mots-clés """ - self.update_node_texte() - if self.state == 'expanded' : - for child in self.children: - if child.displayed != 0 : child.update_texte() - - def update_node_label(self): - """ Met a jour le label du noeud """ - if self.displayed == 0 : return - # nom,fonte et couleur de l'objet du noeud à afficher - labeltext,fonte,couleur = self.item.GetLabelText() - if labeltext == '' : labeltext = ' ' - if fonte == None : fonte = Fonte_Standard - if couleur == None : couleur = 'black' - if hasattr(self,'label') and self.label: - self.label.configure(text=labeltext,font=fonte) - - def update_node_texte(self): - """ Met à jour les noms des SD et valeurs des mots-clés """ - if self.displayed == 0 : return - text = self.item.GetText() - if text == None : text = '' - if hasattr(self,'text') and self.text: - self.text.configure(text=text) - - def update_node_valid(self) : - """Cette methode remet a jour la validite du noeud (icone) - Elle appelle isvalid - """ - if self.displayed == 0 : return - if hasattr(self,'image_id'): - if self.image_id != None : - image = self.geticonimage() - self.canvas.itemconfig(self.image_id,image=image) - - def update_valid(self) : - """Cette methode a pour but de mettre a jour la validite du noeud - et de propager la demande de mise à jour à son parent - """ - self.update_node_valid() - self.parent.update_valid() - - def update(self,event=None) : - """ Classe Node : - Cette méthode est appelée pour demander l update d un noeud - d'un jeu de commandes - Cette demande est transmise au noeud racine (le JDC) qui update - tout l arbre représentant le jeu de commandes - Pendant cette mise à jour, on appelle la méthode isvalid qui - fera l update de tous les objets déclarés modifiés lors des - actions précédentes - La métode isvalid est en général appelée par l intermédiaire de - update_icone -> geticonimage -> GetIconName - """ - #print "update",self - #traceback.print_stack() - self.racine.update_coords() - self.racine.trace_ligne() - self.racine.update_icone() - self.racine.update_texte() - self.racine.update_label_texte() - self.tree.resizescrollregion() - - def efface_node(self): - if self.displayed != 0: - self.label.unbind("<1>", self.select_id) - self.label.unbind("<3>", self.popup_id) - self.label.unbind("",self.enter_id) - self.label.unbind("",self.leave_id) - self.canvas.tag_unbind(self.image_id,"<1>",self.select_id2) - self.canvas.tag_unbind(self.image_id,"<3>",self.popup_id2) - if self.item.IsExpandable(): - self.canvas.tag_unbind(self.icone_id, "<1>", self.callback_id) - self.label.destroy() - self.text.destroy() - - for id in self.id : - self.canvas.delete(id) - self.id=[] - self.label_id=None - self.text_id=None - self.image_id=None - self.icone_id=None - self.label=None - self.text=None - self.displayed=0 - - def efface(self): - """ Efface du canvas les id associés à self : cad les siens et ceux - de ses enfants """ - self.efface_node() - if not self.children : return - for child in self.children: - child.efface() - - def move(self,dy): - """ Déplace de l'incrément dy tous les id en dessous de self """ - # il faut marquer tous les suivants de self - bbox1 = self.canvas.bbox(ALL) - self.canvas.dtag(ALL,'move') - self.canvas.delete('line') - try: - self.canvas.addtag_overlapping('move',bbox1[0],self.y +10,bbox1[2],bbox1[3]) - except: - print "Erreur dans move :" - print self - print self.item - print self.item.getObject() - print self.item.getObject().definition.label - print 'y=',self.y - print 'dy=',dy - # on déplace tous les items de dy - self.canvas.move('move',0,dy) - - def trace_ligne(self): - """ Dessine les lignes verticales entre frères et entre père et premier fils""" - if self.state=='collapsed' : return - if len(self.children)==0 : return - # on est bien dans le cas d'un noeud expansé avec enfants ... - # il faut rechercher l'ordonnée du dernier fils de self - y_end = self.children[-1].y - ligne = self.canvas.create_line(self.x+15,self.y,self.x+15,y_end,tags='line') - self.canvas.tag_lower(ligne) - for child in self.children : - try: - child.trace_ligne() - except: - print "Erreur dans trace_ligne :" - print child - print child.item.getObject() - - def last_child(self): - lchild=self - if self.state == 'expanded' and self.children: - lchild= self.children[-1].last_child() - return lchild - - #------------------------------------------------------------------ - # Méthodes de création et destruction de noeuds - # Certaines de ces méthodes peuvent être appelées depuis l'externe - #------------------------------------------------------------------ - def append_brother(self,name,pos='after',retour='non'): - """ - Permet d'ajouter un objet frère à l'objet associé au noeud self - par défaut on l'ajoute immédiatement après - Méthode externe - """ - # on veut ajouter le frère de nom name directement avant ou après self - index = self.parent.children.index(self) - if pos == 'before': - index = index - elif pos == 'after': - index = index +1 - else: - print str(pos)," n'est pas un index valide pour append_brother" - return 0 - return self.parent.append_child(name,pos=index) - - def append_child(self,name,pos=None,verif='oui',retour='non'): - """ - Methode pour ajouter un objet fils à l'objet associé au noeud self. - On peut l'ajouter en début de liste (pos='first'), en fin (pos='last') - ou en position intermédiaire. - Si pos vaut None, on le place à la position du catalogue. - """ - #print "append_child",self,self.children - if pos == 'first': - index = 0 - elif pos == 'last': - index = len(self.children) - elif type(pos) == types.IntType : - # position fixee - index = pos - elif type(pos) == types.InstanceType: - # pos est un item. Il faut inserer name apres pos - index = self.item.get_index(pos) +1 - elif type(name) == types.InstanceType: - index = self.item.get_index_child(name.nom) - else: - index = self.item.get_index_child(name) - obj=self.item.additem(name,index) - #print obj - if obj is None:obj=0 - if obj == 0:return 0 - #print "append_child",index,self.children - child=self.children[index] - child.select() - return child - - def delete(self): - """ - Méthode externe pour la destruction de l'objet associé au noeud - La mise à jour des noeuds est faite par onSupp sur notification - """ - index = self.parent.children.index(self) - 1 - if index < 0 : index =0 - - parent=self.parent - ret=parent.item.suppitem(self.item) - if ret == 0:return - - brothers=parent.children - if brothers: - toselect=brothers[index] - else: - toselect=parent - toselect.select() - diff --git a/InterfaceTK/uniqueassdpanel.py b/InterfaceTK/uniqueassdpanel.py deleted file mode 100644 index 27edcd97..00000000 --- a/InterfaceTK/uniqueassdpanel.py +++ /dev/null @@ -1,219 +0,0 @@ -# -*- coding: utf-8 -*- -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -# Modules Python -import string,types,os -from Tkinter import * -import Pmw -from copy import copy,deepcopy -import traceback - -# Modules Eficas -from Editeur import Objecttreeitem -import prefs -import panels -import images -from widgets import ListeChoix -from widgets import FenetreDeSelection - -from Noyau.N_CR import justify_text -from Editeur.utils import substract_list - -# Import des panels -from uniquepanel import UNIQUE_Panel - - -class UNIQUE_ASSD_Panel(UNIQUE_Panel): - """ - Classe servant à définir le panneau associé aux objets qui attendent une valeur unique - d'un type dérivé d'ASSD - """ - def valid_valeur_automatique(self): - """ - Réalise la validation d'un concept sans remonter dans le - node parent dans le cas ou il n'y a qu'un concept possible (liste de longueur 1) - Identique à valid_valeur moins appel de self.node.parent.select() - On pourrait supposer que le seul concept présent est valide et donc ne pas - réaliser tous les tests de vérification. - """ - if self.parent.modified == 'n' : self.parent.init_modif() - valeur = self.get_valeur() - self.erase_valeur() - anc_val = self.node.item.get_valeur() - valeur,validite=self.node.item.eval_valeur_item(valeur) - test = self.node.item.set_valeur(valeur) - if not test : - mess = "impossible d'évaluer : %s " %`valeur` - self.parent.appli.affiche_infos("Valeur du mot-clé non autorisée :"+mess) - elif self.node.item.isvalid() : - self.parent.appli.affiche_infos('Valeur du mot-clé enregistrée') - #if self.node.item.get_position()=='global': - #self.node.etape.verif_all() - #elif self.node.item.get_position()=='global_jdc': - #self.node.racine.verif_all() - #else : - #self.node.parent.verif() - #self.node.update() - else : - cr = self.node.item.get_cr() - mess = "Valeur du mot-clé non autorisée :"+cr.get_mess_fatal() - self.reset_old_valeur(anc_val,mess=mess) - - def makeValeurPage(self,page,reel="non"): - """ - Génère la page de saisie de la valeur du mot-clé simple courant qui doit être une - SD de type dérivé d'ASSD - """ - # Récupération de l'aide associée au panneau, de l'aide destinée à l'utilisateur, - # et de la liste des SD du bon type (constituant la liste des choix) - bulle_aide=self.get_bulle_aide() - aide=self.get_aide() - aide= justify_text(texte=aide) - liste_noms_sd = self.node.item.get_sd_avant_du_bon_type() - - # Remplissage du panneau - self.valeur_choisie = StringVar() - self.valeur_choisie.set('') - min,max = self.node.item.GetMinMax() - if (min == 1 and min == max and len(liste_noms_sd)==1 ): - if self.valeur_choisie.get() != liste_noms_sd[0]: - if ('R' not in self.node.item.get_type()) : - self.valeur_choisie.set(liste_noms_sd[0]) - self.valid_valeur_automatique() - - self.frame_valeur = Frame(page) - self.frame_valeur.pack(fill='both',expand=1) - self.frame_valeur.bind("",lambda e,s=self,a=bulle_aide : s.parent.appli.affiche_aide(e,a)) - self.frame_valeur.bind("",self.parent.appli.efface_aide) - self.listbox = Pmw.ScrolledListBox(self.frame_valeur, - items=liste_noms_sd, - labelpos='n', - label_text="Structures de données du type\n requis par l'objet courant :", - listbox_height = 6, - selectioncommand=self.select_valeur_from_list, - dblclickcommand=lambda s=self,c=self.valid_valeur : s.choose_valeur_from_list(c)) - self.listbox.place(relx=0.5,rely=0.3,relheight=0.4,anchor='center') - Label(self.frame_valeur,text='Structure de donnée choisie :').place(relx=0.05,rely=0.6) - Label(self.frame_valeur,textvariable=self.valeur_choisie).place(relx=0.5,rely=0.6) - self.but_val = Button(self.frame_valeur,text = "Valider",command= self.Choisir) - self.but_val.place(relx=0.3,rely=0.8,relwidth=0.35) - - # affichage de la valeur courante - self.display_valeur() - if self.__class__.__name__ == 'UNIQUE_ASSD_Panel_Reel' : - Label(self.frame_valeur,text='Valeur Réelle').place(relx=0.1,rely=0.9) - self.entry = Entry(self.frame_valeur,relief='sunken') - self.entry.place(relx=0.28,rely=0.9,relwidth=0.6) - self.entry.bind("",lambda e,c=self.valid_valeur_reel:c()) - self.entry.bind("",lambda e,c=self.valid_valeur_reel:c()) - - - - def get_bulle_aide(self): - """ - Retourne l'aide associée au panneau - """ - return "Double-cliquez sur la structure de donnée désirée pour valoriser le mot-clé simple courant" - - def get_aide(self): - """ - Retourne la phrase d'aide indiquant de quel type doit être la valeur à donner par l'utilisateur - """ - mc = self.node.item.get_definition() - try : - type = mc.type[0].__name__ - except : - type = str(mc.type[0]) - if len(mc.type)>1 : - for typ in mc.type[1:] : - try : - l=typ.__name__ - except: - l=str(typ) - type = type + ' ou '+l - commentaire="Un objet de type "+type+" est attendu" - aideval=self.node.item.aide() - commentaire=commentaire +"\n"+ aideval - return commentaire - - - def select_valeur_from_list(self): - """ - Affecte à valeur choisie la sélection courante dans la liste des choix proposée - """ - if len(self.listbox.get()) == 0 : return - if len(self.listbox.getcurselection()) == 0 : return - choix = self.listbox.getcurselection()[0] - self.valeur_choisie.set(choix) - self.listbox.component("listbox").focus_set() - - def choose_valeur_from_list(self,command): - """ - Affecte à valeur choisie la sélection courante dans la liste des choix proposée - Exécute command - """ - if len(self.listbox.get()) == 0 : return - if len(self.listbox.getcurselection()) == 0 : return - choix = self.listbox.getcurselection()[0] - self.valeur_choisie.set(choix) - apply(command,(),{}) - - def Choisir(self) : - #Appeler par le bouton Valider - self.choose_valeur_from_list(self.valid_valeur) - - def get_valeur(self): - """ - Retourne la valeur donnée par l'utilisateur au MCS - """ - return self.valeur_choisie.get() - - def display_valeur(self): - """ - Affiche la valeur de l'objet pointé par self - """ - valeur = self.node.item.get_valeur() - if valeur == None or valeur == '' : return # pas de valeur à afficher ... - self.valeur_choisie.set(getattr(valeur,"nom","unknown")) - - def erase_valeur(self): - pass - - def appel_make(self,page): - self.makeValeurPage(page,reel="oui") - -class UNIQUE_ASSD_Panel_Reel(UNIQUE_ASSD_Panel): - - def valid_valeur_reel(self): - if self.parent.modified == 'n' : self.parent.init_modif() - anc_val = self.node.item.get_valeur() - valeurentree = self.entry.get() - self.valeur_choisie.set(valeurentree) - self.valid_valeur() - - def display_valeur(self): - valeur = self.node.item.get_valeur() - if valeur == None or valeur == '' : return # pas de valeur à afficher ... - if type(valeur) == types.FloatType : - self.valeur_choisie.set(valeur) - else : - self.valeur_choisie.set(valeur.nom) - - - diff --git a/InterfaceTK/uniquebasepanel.py b/InterfaceTK/uniquebasepanel.py deleted file mode 100644 index b7a71beb..00000000 --- a/InterfaceTK/uniquebasepanel.py +++ /dev/null @@ -1,153 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -# Modules Python -import string,types,os -from Tkinter import * -from Tkinter import Widget -import Pmw -from copy import copy,deepcopy -import traceback - -# Modules Eficas -from Editeur import Objecttreeitem -import prefs -import panels -import images -from widgets import FenetreDeParametre -from widgets import showerror - -from Noyau.N_CR import justify_text -from Editeur.utils import substract_list - -# Import des panels -from uniquepanel import UNIQUE_Panel - - -class UNIQUE_BASE_Panel(UNIQUE_Panel): - """ - Classe servant à définir le panneau associé aux mots-clés simples qui attendent - une valeur d'un type de base (entier, réel ou string). - """ - def makeValeurPage(self,page): - """ - Génère la page de saisie de la valeur du mot-clé simple courant qui doit être de type - de base cad entier, réel, string ou complexe - """ - # Récupération de l'aide associée au panneau, de l'aide destinée à l'utilisateur, - # et de la liste des SD du bon type (constituant la liste des choix) - bulle_aide=self.get_bulle_aide() - aide=self.get_aide() - aide= justify_text(texte=aide) - liste_noms_sd = self.node.item.get_sd_avant_du_bon_type() - # Remplissage du panneau - self.frame_valeur = Frame(page) - self.frame_valeur.pack(fill='both',expand=1) - self.frame_valeur.bind("",lambda e,s=self,a=bulle_aide : s.parent.appli.affiche_aide(e,a)) - self.frame_valeur.bind("",self.parent.appli.efface_aide) - self.label = Label(self.frame_valeur,text='Valeur :') - #self.label.place(relx=0.1,rely=0.2) - self.label.grid(row=0,padx=5,pady=5) - self.entry = Entry(self.frame_valeur,relief='sunken') - #self.entry.place(relx=0.28,rely=0.2,relwidth=0.6) - self.entry.grid(row=0,column=1,padx=5,pady=5) - self.entry.bind("",lambda e,c=self.valid_valeur:c()) - self.entry.bind("",lambda e,c=self.valid_valeur:c()) - # aide associée au panneau - self.frame_valeur.update() - self.aide = Label(self.frame_valeur, - text = aide, - wraplength=int(self.frame_valeur.winfo_width()*0.8), - justify='center') - #self.aide.place(relx=0.5,rely=0.9,anchor='n') - self.aide.grid(row=4,columnspan=2,padx=5,pady=5) - # bouton parametre - bouton_parametres = Button(self.frame_valeur, text="Parametres", command=self.affiche_parametre) - #bouton_parametres.place(relx=0.28,rely=0.5,relwidth=0.4) - bouton_parametres.grid(row=2,columnspan=2,padx=5,pady=5) - bouton_val = Button(self.frame_valeur, text="Valider", command=self.valide) - #bouton_val.place(relx=0.28,rely=0.6,relwidth=0.4) - bouton_val.grid(row=3,columnspan=2,padx=5,pady=5) - # affichage de la valeur du MCS - self.display_valeur() - - def valide(self): - self.valid_valeur() - - def affiche_parametre(self) : - if self.node.item.get_liste_param_possible() != [ ]: - txtparam="" - for param in self.node.item.get_liste_param_possible(): - txtparam=txtparam+repr(param)+"\n" - if txtparam=="": - showerror("Aucun parametre ","Pas de parametre de ce type") - else : - try : - self.fenetreparam.destroy() - except : - pass - self.fenetreparam=FenetreDeParametre( self, self.node.item, self.parent.appli, txtparam) - - def destroy(self): - try : - self.fenetreparam.destroy() - except : - pass - Widget.destroy(self) - - def get_aide(self): - """ - Retourne la phrase d'aide indiquant de quel type doit être la valeur - du mot-clé simple fournie par l'utilisateur - """ - mc = self.node.item.get_definition() - d_aides = { 'TXM' : "Une chaîne de caractères est attendue", - 'R' : "Un réel est attendu", - 'I' : "Un entier est attendu"} - type = mc.type[0] - commentaire=d_aides.get(type,"Type de base inconnu") - aideval=self.node.item.aide() - commentaire=commentaire +"\n"+ aideval - return commentaire - - def get_bulle_aide(self): - """ - Retourne la bulle d'aide associée au panneau et affichée par clic droit - """ - return """Saisissez la valeur que vous voulez affecter au mot-clé simple - dans la zone de saisie et pressez """ - - def display_valeur(self): - """ - Affiche la valeur de l'objet pointé par self - """ - valeur = self.node.item.get_valeur() - if valeur == None or valeur == '' : # pas de valeur à afficher ... - self.entry.delete(0,END) - self.entry.focus() - return - - valeur_texte=self.get_valeur_texte(valeur) - if valeur_texte != "": - valeur=valeur_texte - self.entry.delete(0,END) - self.entry.insert(0,valeur) - self.entry.focus() - diff --git a/InterfaceTK/uniquecomppanel.py b/InterfaceTK/uniquecomppanel.py deleted file mode 100644 index 80d9aa77..00000000 --- a/InterfaceTK/uniquecomppanel.py +++ /dev/null @@ -1,171 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -# Modules Python -import string,types,os -from Tkinter import * -import Pmw -from copy import copy,deepcopy -import traceback - -# Modules Eficas -from Editeur import Objecttreeitem -import prefs -import panels -import images -from widgets import ListeChoix -from widgets import FenetreDeSelection - -from Noyau.N_CR import justify_text -from Editeur.utils import substract_list - -# Import des panels -from uniquepanel import UNIQUE_Panel - - -class UNIQUE_COMP_Panel(UNIQUE_Panel): - """ - Classe servant à définir le panneau associé aux mots-clés simples - qui attendent une valeur de type complexe - """ - def makeValeurPage(self,page): - """ - Génère la page de saisie de la valeur du mot-clé simple courant qui doit être de type - de base cad entier, réel, string ou complexe - """ - # Récupération de l'aide associée au panneau et de l'aide destinée à l'utilisateur - bulle_aide=self.get_bulle_aide() - aide=self.get_aide() - aide= justify_text(texte=aide) - # Remplissage du panneau - self.frame_valeur = Frame(page) - self.frame_valeur.pack(fill='both',expand=1) - self.frame_valeur.bind("",lambda e,s=self,a=bulle_aide : s.parent.appli.affiche_aide(e,a)) - self.frame_valeur.bind("",self.parent.appli.efface_aide) - self.label = Label(self.frame_valeur,text='Complexe de la forme : a+bj') - self.label1 = Label(self.frame_valeur,text='Imaginaire') - self.label2 = Label(self.frame_valeur,text='Phase') - self.label3 = Label(self.frame_valeur,text='OU') - self.label.place (relx=0.15,rely=0.1) - self.label1.place(relx=0.6,rely=0.50) - self.label2.place(relx=0.6,rely=0.57) - self.label3.place(relx=0.15,rely=0.4) - self.typ_cplx=StringVar() - self.typ_cplx.set('RI') - rb1 = Radiobutton(self.frame_valeur, text='RI : Réel',variable=self.typ_cplx,value='RI') - rb2 = Radiobutton(self.frame_valeur, text='MP : Module',variable=self.typ_cplx,value='MP') - rb1.place(relx=0.15,rely = 0.50) - rb2.place(relx=0.15,rely = 0.57) - self.entry1 = Pmw.EntryField(self.frame_valeur,validate='real') - self.entry2 = Pmw.EntryField(self.frame_valeur,validate='real') - self.entry3 = Pmw.EntryField(self.frame_valeur) - self.entry1.component('entry').bind("",lambda e,s=self:s.entry2.component('entry').focus()) - self.entry1.component('entry').bind("",lambda e,s=self:s.entry2.component('entry').focus()) - self.entry2.component('entry').bind("",lambda e,c=self.valid_valeur:c()) - self.entry2.component('entry').bind("",lambda e,c=self.valid_valeur:c()) - self.entry3.component('entry').bind("",lambda e,c=self.valid_complexe:c()) - self.entry3.component('entry').bind("",lambda e,c=self.valid_complexe:c()) - self.entry1.place(relx=0.15,rely = 0.65,relwidth=0.35) - self.entry2.place(relx=0.60,rely = 0.65,relwidth=0.35) - self.entry3.place(relx=0.15,rely = 0.20,relwidth=0.60) - self.entry1.focus() - self.bouton_val=Button(self.frame_valeur,text="Valider",command=self.valider,width=14) - self.bouton_val.place(relx=0.4,rely=0.8) - self.frame_valeur.update() - self.aide = Label(self.frame_valeur, - text = aide, - wraplength=int(self.frame_valeur.winfo_width()*0.8), - justify='center') - self.aide.place(relx=0.5,rely=0.9,anchor='n') - # affichage de la valeur du MCS - self.display_valeur() - - def valider(self): - if ((self.entry3.get() != None) and (self.entry3.get() != "" )): - self.erase_valeur() - self.valid_complexe() - else : - self.valid_valeur() - - - def display_valeur(self): - """ - Affiche la valeur de l'objet pointé par self - """ - valeur = self.node.item.get_valeur() - if valeur == None or valeur == '' : return # pas de valeur à afficher ... - self.entry1.delete(0,END) - self.entry2.delete(0,END) - self.entry3.delete(0,END) - if type(valeur) not in (types.ListType,types.TupleType) : - self.display_complexe() - else: - typ_cplx,x1,x2=valeur - self.typ_cplx.set(typ_cplx) - self.entry1.setentry(x1) - self.entry2.setentry(x2) - - def display_complexe(self): - valeur = self.node.item.get_valeur() - self.entry3.setentry(valeur) - - def get_bulle_aide(self): - """ - Retourne la bulle d'aide du panneau - """ - return """-Choisissez votre format de saisie du complexe : - \t 'RI' = parties réelle et imaginaire - \t 'MP' = module/phase (en degrés) - - Saisissez ensuite dans les deux zones de saisie les deux nombres attendus""" - - def get_aide(self): - """ - Retourne la phrase d'aide décrivant le type de la valeur que peut prendre - le mot-clé simple courant - """ - commentaire='Un complexe est attendu' - aideval=self.node.item.aide() - commentaire=commentaire +"\n"+ aideval - return commentaire - - def get_valeur(self): - """ - Retourne le complexe saisi par l'utilisateur - """ - l=[] - l.append(self.typ_cplx.get()) - try : - l.append(string.atof(self.entry1.get())) - l.append(string.atof(self.entry2.get())) - except : - return None - return `tuple(l)` - - def erase_valeur(self): - """ - Efface les entries de saisie - """ - self.typ_cplx.set('RI') - self.entry1.delete(0,END) - self.entry2.delete(0,END) - - def valid_complexe(self): - valeurentree=self.entry3.get() - self.valid_valeur(valeurentree=valeurentree) diff --git a/InterfaceTK/uniqueintopanel.py b/InterfaceTK/uniqueintopanel.py deleted file mode 100644 index 76133cd5..00000000 --- a/InterfaceTK/uniqueintopanel.py +++ /dev/null @@ -1,96 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -# Modules Python -import string,types,os -from Tkinter import * -import Pmw -from copy import copy,deepcopy -import traceback - -# Modules Eficas -from Editeur import Objecttreeitem -import prefs -import panels -import images -from widgets import ListeChoix -from widgets import FenetreDeSelection - -from Noyau.N_CR import justify_text -from Editeur.utils import substract_list - -# Import des panels -from uniquepanel import UNIQUE_Panel - -class UNIQUE_INTO_Panel(UNIQUE_Panel): - """ - Classe définissant le panel associé aux mots-clés qui demandent - à l'utilisateur de choisir une seule valeur parmi une liste de valeurs - discrètes - """ - def makeValeurPage(self,page): - """ - Génère la page de saisie d'une seule valeur parmi un ensemble - discret de possibles - """ - # récupération de la bulle d'aide et de l'objet mc - bulle_aide=self.get_bulle_aide() - objet_mc = self.node.item.get_definition() - # remplissage du panel - self.frame_valeur = Frame(page) - self.frame_valeur.pack(fill='both',expand=1) - self.frame_valeur.bind("",lambda e,s=self,a=bulle_aide : - s.parent.appli.affiche_aide(e,a)) - self.frame_valeur.bind("",self.parent.appli.efface_aide) - #l_choix=list(objet_mc.into) - #l_choix.sort() - l_choix=self.node.item.get_liste_possible([]) - self.label = Label(self.frame_valeur,text='Choisir une valeur :') - self.label.pack(side='top') - self.frame = Frame(page) - self.frame.place(relx=0.33,rely=0.2,relwidth=0.33,relheight=0.6) - - - liste_commandes = (("",self.selectChoix), - ("",self.deselectChoix), - ("",self.record_valeur)) - self.Liste_choix = ListeChoix(self,self.frame,l_choix, - liste_commandes = liste_commandes, - titre="Valeurs possibles",optionReturn="oui") - self.Liste_choix.affiche_liste() - if len(l_choix) == 1 : - self.Liste_choix.surligne(l_choix[0]) - self.bouton_val = Button(self.frame_valeur, - text = "Valider", - command=self.record_valeur_ligne, - width=14) - self.bouton_val.place(relx=0.33,rely=0.85) - - def record_valeur_ligne(self): - valeur=self.Liste_choix.arg_selected - self.record_valeur(valeur) - - def get_bulle_aide(self): - """ - Retourne la bulle d'aide affectée au panneau courant (affichée par clic droit) - """ - return """Double-cliquez sur la valeur désirée - pour valoriser le mot-clé simple courant""" - diff --git a/InterfaceTK/uniquepanel.py b/InterfaceTK/uniquepanel.py deleted file mode 100644 index 90b3b9d9..00000000 --- a/InterfaceTK/uniquepanel.py +++ /dev/null @@ -1,93 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -# Modules Python -import string,types,os -from Tkinter import * -import Pmw -from copy import copy,deepcopy -import traceback - -# Modules Eficas -from Editeur import Objecttreeitem -import prefs -import panels -import images -from widgets import ListeChoix -from widgets import FenetreDeSelection - -from Noyau.N_CR import justify_text -from Editeur.utils import substract_list - -# Import des panels -from newsimppanel import newSIMPPanel - - -class UNIQUE_Panel(newSIMPPanel): - """ - Classe virtuelle servant de classe mère à toutes celles définissant un panneau - permettant l'affichage et la saisie d'une valeur unique pour le mot-clé simple - """ - - def erase_valeur(self): - """ - Efface l'entry de saisie - """ - self.entry.delete(0,END) - - def get_valeur(self): - """ - Retourne la valeur donnée par l'utilisateur - """ - return self.entry.get() - - - def valid_valeur(self,valeurentree=None): - """ - Teste si la valeur fournie par l'utilisateur est une valeur permise : - - si oui, l'enregistre - - si non, restaure l'ancienne valeur - """ - if self.parent.modified == 'n' : self.parent.init_modif() - anc_val = self.node.item.get_valeur() - if valeurentree== None : - valeurentree = self.get_valeur() - valeur,validite=self.node.item.eval_valeur(valeurentree) - if not validite : - commentaire = "impossible d'évaluer : %s " %`valeurentree` - self.display_valeur() - self.parent.appli.affiche_infos(commentaire) - return - - test = self.node.item.set_valeur(valeur) - if test : - self.set_valeur_texte(str(valeurentree)) - - if not test : - mess = "impossible d'évaluer : %s " %`valeur` - self.parent.appli.affiche_infos("Valeur du mot-clé non autorisée : "+mess) - elif self.node.item.isvalid() : - self.parent.appli.affiche_infos('Valeur du mot-clé enregistrée') - else : - cr = self.node.item.get_cr() - mess = "Valeur du mot-clé non autorisée "+cr.get_mess_fatal() - self.reset_old_valeur(anc_val,mess=mess) - - self.display_valeur() diff --git a/InterfaceTK/uniquesdcopanel.py b/InterfaceTK/uniquesdcopanel.py deleted file mode 100644 index a9e326c5..00000000 --- a/InterfaceTK/uniquesdcopanel.py +++ /dev/null @@ -1,246 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -# Modules Python -import string,types,os -from Tkinter import * -import Pmw -from copy import copy,deepcopy -import traceback - -# Modules Eficas -from Editeur import Objecttreeitem -import prefs -import panels -import images -from widgets import ListeChoix -from widgets import FenetreDeSelection - -from Noyau.N_CR import justify_text -from Editeur.utils import substract_list - -# Import des panels -from uniqueassdpanel import UNIQUE_ASSD_Panel - - -class UNIQUE_SDCO_Panel(UNIQUE_ASSD_Panel): - """ - Classe servant à définir le panneau correspondant à un mot-clé simple - qui attend une valeur unique de type dérivé d'ASSD ou non encore - existante (type CO(...) utilisé dans les macros uniquement) - """ - def makeValeurPage(self,page): - """ - Génère la page de saisie de la valeur du mot-clé simple courant qui doit être une SD de type dérivé - d'ASSD - """ - # Récupération de l'aide associée au panneau, de l'aide destinée à l'utilisateur, - # et de la liste des SD du bon type (constituant la liste des choix) - bulle_aide=self.get_bulle_aide() - aide=self.get_aide() - aide= justify_text(texte=aide) - liste_noms_sd = self.node.item.get_sd_avant_du_bon_type() - # Remplissage du panneau - self.frame_valeur = Frame(page) - self.frame_valeur.pack(fill='both',expand=1) - self.frame_valeur.bind("",lambda e,s=self,a=bulle_aide : s.parent.appli.affiche_aide(e,a)) - self.frame_valeur.bind("",self.parent.appli.efface_aide) - # affichage de la liste des SD existantes et du bon type - self.listbox = Pmw.ScrolledListBox(self.frame_valeur, - items=liste_noms_sd, - labelpos='n', - label_text="Structures de données du type\n requis par l'objet courant :", - listbox_height = 6, - selectioncommand=self.select_valeur_from_list, - dblclickcommand=lambda s=self,c=self.valid_valeur : s.choose_valeur_from_list(c)) - self.listbox.component("listbox").bind("",lambda e,s=self,c=self.valid_valeur : s.choose_valeur_from_list(c)) - if liste_noms_sd != [] : - self.listbox.place(relx=0.5,rely=0.3,relheight=0.4,anchor='center') - self.b_co = Pmw.OptionMenu(self.frame_valeur,labelpos='w',label_text = "Nouveau concept : ", items = ('NON','OUI'), - menubutton_width=10) - else : - self.b_co = Pmw.OptionMenu(self.frame_valeur,labelpos='w',label_text = "Nouveau concept : ", items = ('OUI',), - menubutton_width=10) - # affichage du bouton 'Nouveau concept' - self.b_co.configure(command = self.ask_new_concept) - if liste_noms_sd != [] : - self.b_co.place(relx=0.05,rely=0.6,anchor='w') - else : - self.b_co.place(relx=0.05,rely=0.3,anchor='w') - self.label_co = Label(self.frame_valeur,text='Nom du nouveau concept :') - self.entry_co = Entry(self.frame_valeur) - self.entry_co.bind('',self.valid_nom_concept_co) - self.entry_co.bind('',self.valid_nom_concept_co) - # affichage du label de la structure de donnée choisie - self.l_resu = Label(self.frame_valeur,text='Structure de donnée choisie :') - self.valeur_choisie = StringVar() - self.label_valeur = Label(self.frame_valeur,textvariable=self.valeur_choisie) - self.frame_valeur.update() - self.aide = Label(self.frame_valeur, - text = aide, - wraplength=int(self.frame_valeur.winfo_width()*0.8), - justify='center') - self.aide.place(relx=0.5,rely=0.85,anchor='n') - - self.but_val = Button(self.fr_but,text = "Valider",command= self.valid_nom_concept_co) - self.but_val.pack(side='right',padx=5, pady=5) - - # affichage de la valeur courante - self.display_valeur() - if liste_noms_sd == [] : - self.b_co.invoke('OUI') - - def get_bulle_aide(self): - """ - Retourne la bulle d'aide du panneau - """ - return """Double-cliquez sur la structure de donnée désirée - pour valoriser le mot-clé simple courant ou cliquez sur NOUVEAU CONCEPT pour - entrer le nom d'un concept non encore existant""" - - def valid_valeur(self): - """ - Teste si la valeur fournie par l'utilisateur est une valeur permise : - - si oui, l'enregistre - - si non, restaure l'ancienne valeur - """ - if self.parent.modified == 'n' : self.parent.init_modif() - valeur = self.get_valeur() - #print "valid_valeur",valeur - - self.erase_valeur() - anc_val = self.node.item.get_valeur() - test_CO=self.node.item.is_CO(anc_val) - #PN essai pour bug dans MACRO_PROJ_BASE - valeur,validite=self.node.item.eval_valeur(valeur) - test = self.node.item.set_valeur(valeur) - if not test : - mess = "impossible d'évaluer : %s " %`valeur` - self.parent.appli.affiche_infos("Valeur du mot-clé non autorisée :"+mess) - return - #PN essai pour bug dans MACRO_PROJ_BASE - #elif self.node.item.isvalid() : - elif validite: - self.parent.appli.affiche_infos('Valeur du mot-clé enregistrée') - if test_CO: - # il faut egalement propager la destruction de l'ancien concept - self.node.item.delete_valeur_co(valeur=anc_val) - # et on force le recalcul des concepts de sortie de l'etape - self.node.item.object.etape.get_type_produit(force=1) - # et le recalcul du contexte - self.node.item.object.etape.parent.reset_context() - self.node.parent.select() - else : - cr = self.node.item.get_cr() - mess = "Valeur du mot-clé non autorisée :"+cr.get_mess_fatal() - self.reset_old_valeur(anc_val,mess=mess) - return - - def valid_nom_concept_co(self,event=None): - """ - Lit le nom donné par l'utilisateur au concept de type CO qui doit être - la valeur du MCS courant et stocke cette valeur - """ - #print "valid_nom_concept_co" - if self.parent.modified == 'n' : self.parent.init_modif() - anc_val = self.node.item.get_valeur() - if anc_val != None: - # il faut egalement propager la destruction de l'ancien concept - self.node.item.delete_valeur_co(valeur=anc_val) - # et on force le recalcul des concepts de sortie de l'etape - self.node.item.object.etape.get_type_produit(force=1) - # et le recalcul du contexte - self.node.item.object.etape.parent.reset_context() - nom_concept = self.entry_co.get() - #print "valid_nom_concept_co",nom_concept - test,mess=self.node.item.set_valeur_co(nom_concept) - if not test: - # On n'a pas pu créer le concept - self.parent.appli.affiche_infos(mess) - return - elif self.node.item.isvalid() : - self.parent.appli.affiche_infos('Valeur du mot-clé enregistrée') - self.node.parent.select() - else : - cr = self.node.item.get_cr() - mess = "Valeur du mot-clé non autorisée :"+cr.get_mess_fatal() - self.reset_old_valeur(anc_val,mess=mess) - return - - def ask_new_concept(self,tag): - """ - Crée une entry dans le panneau d'un MCS qui attend un concept OU un CO() afin de - permettre à l'utilisateur de donner le nom du nouveau concept - """ - new_concept = self.b_co.getcurselection() - if new_concept == 'OUI': - self.label_co.place(relx=0.05,rely=0.7) - self.entry_co.place(relx=0.45,rely=0.7,relwidth=0.25) - self.l_resu.place_forget() - self.label_valeur.place_forget() - self.entry_co.focus() - elif new_concept == 'NON': - # On est passe de OUI à NON, on supprime la valeur -# PN correction de bug (on passe de non a non et cela supprime la valeur) -# ajout du if de le ligne suivane - if self.node.item.is_CO(): - self.node.item.delete_valeur_co() - self.record_valeur(name=None,mess="Suppression CO enregistrée") - self.label_co.place_forget() - self.entry_co.place_forget() - self.l_resu.place(relx=0.05,rely=0.7) - self.label_valeur.place(relx=0.45,rely=0.7) - - def display_valeur(self): - """ - Affiche la valeur de l'objet pointé par self - """ - valeur = self.node.item.get_valeur() - #print "display_valeur",valeur - if valeur == None or valeur == '': - self.valeur_choisie.set('') - return # pas de valeur à afficher ... - # il faut configurer le bouton si la valeur est un objet CO - # sinon afficher le nom du concept dans self.valeur_choisie - if self.node.item.is_CO(): - #print "display_valeur.is_CO" - self.b_co.invoke('OUI') - self.entry_co.insert(0,valeur.nom) - else: - self.valeur_choisie.set(valeur.nom) - - def record_valeur(self,name=None,mess='Valeur du mot-clé enregistrée'): - """ - Enregistre val comme valeur de self.node.item.object SANS faire de test de validité - """ - if self.parent.modified == 'n' : self.parent.init_modif() - if name != None: - valeur =name - else : - self.entry_co.delete(0,END) - valeur= self.entry_co.get() - self.node.item.set_valeur_co(valeur) - self.parent.appli.affiche_infos(mess) - # On met a jour le display dans le panneau - self.display_valeur() - if self.node.item.isvalid(): - self.node.parent.select() - - diff --git a/InterfaceTK/widgets.py b/InterfaceTK/widgets.py deleted file mode 100644 index c0dda777..00000000 --- a/InterfaceTK/widgets.py +++ /dev/null @@ -1,1388 +0,0 @@ -# -*- coding: utf-8 -*- -# CONFIGURATION MANAGEMENT OF EDF VERSION -# ====================================================================== -# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG -# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY -# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY -# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR -# (AT YOUR OPTION) ANY LATER VERSION. -# -# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT -# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF -# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU -# GENERAL PUBLIC LICENSE FOR MORE DETAILS. -# -# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE -# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER, -# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE. -# -# -# ====================================================================== -# ---------------------------------------------------------- -# Cette classe sert à définir les widgets utilisés par -# EFICAS -# ---------------------------------------------------------- - -import Tkinter -from Tkinter import * -import Pmw -import os,sys,re,string -import types,fnmatch -import traceback -from tkFileDialog import * -from tkMessageBox import showinfo,askyesno,showerror,askretrycancel - -import fontes -import prefs -from Editeur.utils import save_in_file -from centerwindow import centerwindow - -from Noyau.N_utils import repr_float -from Accas import AsException - -# Surcharge de la fonction askyesno qui retourne un resultat errone en Python 2.3 avec Tk 8.4 -# et Tkinter.wantobject==1 -import tkMessageBox -def askyesno(title=None, message=None, **options): - "Ask a question; return true if the answer is yes" - s = tkMessageBox._show(title, message, tkMessageBox.QUESTION, tkMessageBox.YESNO, **options) - if s == tkMessageBox.YES:return 1 - if s == tkMessageBox.NO:return 0 - if s:return 1 - return 0 - - -class Fenetre : - """ Cette classe permet de créer une fenêtre Toplevel dans laquelle - on peut afficher un texte et qui permet de le sauver""" - def __init__(self,appli,titre="",texte="",wrap=WORD,width=100,height=30): - self.appli=appli - if self.appli.test==1 : return - self.fenetre = Toplevel() - self.fenetre.withdraw() - #self.fenetre.configure(width = 800,height=500) - self.fenetre.protocol("WM_DELETE_WINDOW", self.quit) - self.fenetre.title("Visualisation du "+titre) - self.texte = string.replace(texte,'\r\n','\n') - self.titre = titre - fonte=fontes.standardcourier10 - # définition des frames - self.frame_texte = Frame(self.fenetre) - self.frame_boutons = Frame(self.fenetre) - #self.frame_texte.place(relx=0,rely=0,relwidth=1,relheight=0.9) - #self.frame_boutons.place(relheight=0.1,relx=0,rely=0.9,relwidth=1.) - # définition de la zone texte et du scrollbar - self.zone_texte = Text(self.frame_texte,font=fonte,wrap=wrap, - height=height,width=width) - self.zone_texte.bind("", self.page_up) - self.zone_texte.bind("", self.page_down) - self.zone_texte.bind("", self.unit_up) - self.zone_texte.bind("", self.unit_down) - self.scroll_v = Scrollbar (self.frame_texte,command = self.zone_texte.yview) - #self.scroll_h = Scrollbar (self.frame_texte,command = self.zone_texte.xview) - self.scroll_v.pack(side='right',fill ='y') - #self.scroll_h.pack(side='bottom',fill ='x') - self.zone_texte.pack(side='top',fill='both',expand=1,padx=5,pady=10) - self.zone_texte.configure(yscrollcommand=self.scroll_v.set) - # définition des boutons - self.but_quit = Button(self.frame_boutons,text = "Fermer",command=self.quit, - default='active') - self.but_save = Button(self.frame_boutons,text = "Sauver",command = self.save) - #self.but_quit.place(relx=0.4,rely=0.5,anchor='center') - #self.but_save.place(relx=0.6,rely=0.5,anchor='center') - self.but_quit.pack(side='left',padx=25, pady=5) - self.but_save.pack(side='right',padx=25, pady=5) - self.frame_texte.pack(side='top',fill='both',expand=1) - self.frame_boutons.pack(side='bottom') - self.zone_texte.focus_set() - self.fenetre.bind('',self.quit) #dismiss window - - # affichage du texte - self.affiche_texte(self.texte) - self.zone_texte.config(state=DISABLED) - centerwindow(self.fenetre) - self.fenetre.deiconify() - - def page_up(self,event): - event.widget.yview_scroll(-1, "page") - return "break" #Pour eviter la propagation de l'evenement a la fenetre principale - def page_down(self,event): - event.widget.yview_scroll(1, "page") - return "break" #Pour eviter la propagation de l'evenement a la fenetre principale - def unit_up(self,event): - event.widget.yview_scroll(-1, "unit") - return "break" #Pour eviter la propagation de l'evenement a la fenetre principale - def unit_down(self,event): - event.widget.yview_scroll(1, "unit") - return "break" #Pour eviter la propagation de l'evenement a la fenetre principale - - def wait(self): - self.fenetre.grab_set() - self.zone_texte.focus_set() - self.fenetre.wait_window(self.fenetre) - - def quit(self,event=None): - self.fenetre.destroy() - return "break" #Pour eviter la propagation de l'evenement a la fenetre principale - - def efface_scroll(self): - """ Efface le scroll lorsqu'il n'est pas nécessaire : ne marche pas""" - self.scroll_v.pack_forget() - #self.scroll_h.pack_forget() - - def affiche_texte(self,texte): - """ Affiche le texte dans la fenêtre """ - if texte != "" : - self.zone_texte.insert(END,texte) - try: - self.fenetre.update_idletasks() - x0,y0,x1,y1 = self.zone_texte.bbox(END) - if (y1-y0) < 300 : self.efface_scroll() - except: - pass - - def save(self): - """ Permet de sauvegarder le texte dans un fichier dont on a demandé le nom - à l'utilisateur """ - file = asksaveasfilename(parent=self.fenetre,defaultextension = '.comm', - #initialdir = self.appli.CONFIGURATION.rep_user, - initialdir = self.appli.CONFIGURATION.initialdir, - title="Sauvegarde du "+self.titre) - if file : - if not save_in_file(file,self.texte,None) : - showerror("Sauvegarde impossible", - "Impossible de sauvegarder le texte dans le fichier spécifié\n"+ - "Vérifiez les droits d'écriture",parent=self.fenetre) - else: - showinfo("Sauvegarde effectuée","Sauvegarde effectuée dans le fichier %s" %file,parent=self.fenetre) - - def destroy(self): - try : - self.fenetre.destroy() - except : - pass - -class FenetreSurLigneWarning(Fenetre): - - def affiche_texte(self,texte): - """ Affiche le texte dans la fenêtre """ - ligne=0 - if texte != "" : - texte_cr=texte.splitlines() - for l in texte_cr: - ligne=ligne+1 - l=l+"\n" - self.zone_texte.insert(END,l) - if (l.find("WARNING") > -1) or (l.find("ERROR") > -1) : - self.zone_texte.tag_add( "Rouge", str(ligne)+".0", "end-1c" ) - self.zone_texte.tag_config("Rouge", foreground='red') - try: - self.fenetre.update_idletasks() - x0,y0,x1,y1 = self.zone_texte.bbox(END) - if (y1-y0) < 300 : self.efface_scroll() - except: - pass - -class FenetreYesNo(Fenetre): - def __init__(self,appli,titre="",texte="",yes="Yes",no="No"): - self.appli=appli - self.fenetre = Toplevel() - self.fenetre.configure(width = 800,height=500) - self.fenetre.protocol("WM_DELETE_WINDOW", self.quit) - self.fenetre.title(titre) - self.texte = string.replace(texte,'\r\n','\n') - self.titre = titre - fonte=fontes.standardcourier10 - # définition des frames - self.frame_texte = Frame(self.fenetre) - self.frame_boutons = Frame(self.fenetre) - self.frame_boutons.place(relx=0,rely=0, relwidth=1.,relheight=0.1) - self.frame_texte.place( relx=0,rely=0.1, relwidth=1, relheight=0.9) - # définition de la zone texte et du scrollbar - self.zone_texte = Text(self.frame_texte,font=fonte) - self.zone_texte.bind("", self.page_up) - self.zone_texte.bind("", self.page_down) - self.zone_texte.bind("", self.unit_up) - self.zone_texte.bind("", self.unit_down) - self.scroll_v = Scrollbar (self.frame_texte,command = self.zone_texte.yview) - #self.scroll_h = Scrollbar (self.frame_texte,command = self.zone_texte.xview) - self.scroll_v.pack(side='right',fill ='y') - #self.scroll_h.pack(side='bottom',fill ='x') - self.zone_texte.pack(side='top',fill='both',expand=1,padx=5,pady=10) - self.zone_texte.configure(yscrollcommand=self.scroll_v.set) - # définition des boutons - self.but_yes = Button(self.frame_boutons,text = yes,command=self.yes) - self.but_no = Button(self.frame_boutons,text = no,command = self.no) - self.but_yes.place(relx=0.4,rely=0.5,anchor='center') - self.but_no.place(relx=0.6,rely=0.5,anchor='center') - # affichage du texte - self.affiche_texte(self.texte) - centerwindow(self.fenetre) - - def yes(self): - self.result=1 - self.quit() - - def no(self): - self.result=0 - self.quit() - -class FenetreDeSelection(Fenetre): - """ Classe dérivée de Fenêtre permettant la récupération d'une zone de texte sélectionnée. - Cette classe est utilisée pour affecter une liste de valeurs à un mot-clé. - """ - def __init__(self,panel,item,appli,titre="",texte="",cardinal=1): - Fenetre.__init__(self,appli,titre=titre,texte=texte) - self.frame_boutons.place_forget() - self.frame_texte.place_forget() - self.frame_texte.place(relx=0,rely=0,relwidth=1,relheight=0.8) - self.frame_boutons.place(relheight=0.2,relx=0,rely=0.8,relwidth=1.) - - self.cardinal=cardinal - self.fenetre.configure(width = 320,height=400) - centerwindow(self.fenetre) - self.panel = panel - self.item = item - self.fenetre.title(titre) - self.but_save.configure(text="Ajouter",command=self.traite_selection) - # séparateur par défaut - self.separateur = ';' - # création de la zone de saisie du séparateur - l_separateurs_autorises = self.get_separateurs_autorises() - self.choix_sep = Pmw.ComboBox(self.frame_boutons, - label_text = "Séparateur :", - labelpos = 'w', - listheight = 100, - selectioncommand = self.choose_separateur, - scrolledlist_items = l_separateurs_autorises) - self.choix_sep.component('entry').configure(width=6) - self.choix_sep.place(relx=0.01,rely=0.5,anchor='w') - self.choix_sep.selectitem(self.separateur) - # Replacement - self.but_quit.place_forget() - self.but_save.place_forget() - self.but_all = Button(self.frame_boutons,text = "Tout Sélectionner", command=self.tout) - self.but_save.place(relx=0.6,rely=0.6,anchor='center') - self.but_quit.place(relx=0.8,rely=0.6,anchor='center') - self.but_all.place(relx=0.7,rely=0.2,anchor='center') - self.choose_separateur('espace') - - - def get_separateurs_autorises(self): - """ - Retourne la liste des séparateurs autorisés - """ - return ['espace',';',','] - - def choose_separateur(self,nom_sep): - """ - Affecte à self.separateur le caractère séparateur correspondant à nom_sep - """ - if nom_sep == 'espace' : - self.separateur = ' ' - else: - self.separateur = nom_sep - - def tout(self): - liste=[] - texte=self.texte.splitlines() - for l in texte : - for mot in string.split(l,self.separateur): - if mot != '' and mot != ' ' and mot != self.separateur : - liste.append(mot) - self.traite_selection(liste) - - def traite_selection(self,liste=None): - """ Cette méthode effectue tous les traitements nécessaires pour vérifier - et affecter la liste de valeurs à l'objet réprésenté par self.item - """ - # Récupère la liste des chaines de caractères de la zone sélectionnée - message="" - if liste == None: - message,liste = self.recupere_liste() - if self.test_probleme(message,"Sélectionnez des données") == 0: - return - # Vérifie que le nombre de données est dans les limites attendues - message = self.verif_liste(liste) - if self.test_probleme(message,"Vérifiez le nombre de données") == 0: - return - # Crée une liste de valeurs du type attendu - message,liste_valeurs = self.creation_liste_valeurs(liste) - if self.test_probleme(message,"Vérifiez le type des données") == 0: - return - # Vérifie que chaque valeur est dans le domaine exigé - message = self.verif_valeurs(liste_valeurs) - if self.test_probleme(message,"Vérifiez le domaine des valeurs") == 0: - return - # Ajoute les valeurs dans la liste de valeurs du mot-clé - if self.cardinal != 1 : - nb=self.cardinal - l_valeurs=[] - # a ameliorer - if (len(liste_valeurs)%nb != 0): - message="La cardinalité n'est pas correcte" - self.test_probleme(message,"On attend des tuples") - return - for i in range(len(liste_valeurs)/nb) : - if (nb==2): - t=(liste_valeurs[i*nb], liste_valeurs[i*nb+1]) - elif (nb ==3): - t=(liste_valeurs[i*nb], liste_valeurs[i*nb+1], liste_valeurs[i*nb+2]) - else : - print "probleme : prevenir la maintenance Eficas" - return - l_valeurs.append(t) - liste_valeurs=l_valeurs - self.ajouter_valeurs(liste_valeurs) - self.appli.affiche_infos("Liste de valeurs acceptée") - - def test_probleme(self, message, message_eficas): - """ Cette méthode affiche un message d'erreur si message != '' - et retourne 0, sinon retourne 1 sans rien afficher. - """ - if message != "": - showinfo("Problème",message,parent=self.fenetre) - self.fenetre.tkraise() - self.appli.affiche_infos(message_eficas) - return 0 - else: - return 1 - - def recupere_liste(self): - """ Cette méthode récupère le texte de la zone sélectionnée, construit et - retourne une liste avec les chaines qui se trouvent entre les séparateurs. - S'il n'y a pas de données selectionnées, elle retourne un message d'erreur - et une liste vide. - """ - message = "" - try: - selection=self.fenetre.selection_get() - except: - message = "Pas de donnée sélectionnée" - return message,None - # les retours chariots doivent être interprétés comme des séparateurs - selection = string.replace(selection,'\n',self.separateur) - # on splitte la sélection suivant le caractère séparateur - liste_chaines = string.split(selection,self.separateur) - l_chaines = [] - for chaine in liste_chaines: - chaine = string.strip(chaine) - if chaine != '' : l_chaines.append(chaine) - return message,l_chaines - - def verif_liste(self, liste): - """ Cette méthode effectue des tests sur le nombre d'éléments de la liste - et retourne 1 si la liste est correcte, sinon 0 et le message d'erreur - correspondant. - """ - message = "" - # nombre d'éléments sélectionnés - nombre_elements = len(liste) - # nombre d'éléments déja dans la liste du panel - nombre_in_liste = len(self.panel.Liste_valeurs.get_liste()) - multiplicite = self.item.GetMultiplicite() - if (nombre_elements % multiplicite) != 0: - message = "Vous devez sélectionner "+str(multiplicite)+" * n données" - return message - nombre_valeurs = nombre_elements / multiplicite - cardinalite = self.item.GetMinMax() - if nombre_valeurs < cardinalite[0]: - message = "Vous devez sélectionner au moins "+str(cardinalite[0])+" valeurs" - return message - if cardinalite[1] != "**" and nombre_valeurs > (long(cardinalite[1])-nombre_in_liste): - message = "La liste ne peut avoir plus de "+str(cardinalite[1])+" valeurs" - return message - - return message - - def creation_liste_valeurs(self, liste): - """ Cette méthode crée et retourne une liste de valeurs du type attendu - par le mot-clé. La liste de valeurs est créée à partir de la liste - de chaines de caractères transmise. - """ - type_attendu = self.item.GetType()[0] - if type_attendu == 'R': - return self.convertir(liste, f_conversion= float) - elif type_attendu == 'I': - return self.convertir(liste, f_conversion= int) - elif type_attendu == 'TXM': - return self.convertir(liste) - else: - message = "Seuls les entiers, les réels et les chaines de caractères sont convertis" - return message,None - - def convertir(self, liste, f_conversion=None): - """ Cette méthode essaie de convertir les éléments de la liste avec la - fonction f_conversion si elle existe, et retourne la liste des - éléments dans le type voulu en cas de succès, sinon retourne None. - """ - liste_valeurs = [] - message = "" - for chaine in liste: - if f_conversion: - try: - liste_valeurs.append(f_conversion(chaine)) - except: - message = "Impossible de convertir "+chaine+" dans le type attendu" - return message,None - else: - liste_valeurs.append(chaine) - return message,liste_valeurs - - def verif_valeurs(self, liste_valeurs): - """ Cette méthode teste la validité de tous les éléments de la liste, - retourne un message vide s'ils sont valides - ou un message non vide au premier élément non valide rencontré - """ - message = "" - for valeur in liste_valeurs: - test,message = self.item.object.verif_type(valeur) - if test == 0: return message - return message - - def ajouter_valeurs(self, liste_valeurs): - """ Cette méthode ajoute les nouvelles valeurs à la liste existante.""" - liste = self.panel.Liste_valeurs.get_liste() - liste.extend(liste_valeurs) - self.panel.Liste_valeurs.put_liste(liste) - -class FenetreDeParametre(Fenetre) : - def __init__(self,parent,item,appli,texte): - self.parent=parent - self.appli=appli - self.fenetre = Toplevel() - self.fenetre.configure(width = 250,height=100) - self.fenetre.protocol("WM_DELETE_WINDOW", self.quit) - self.fenetre.title("Parametres") - self.titre = "Parametres" - self.texte = string.replace(texte,'\r\n','\n') - fonte=fontes.standardcourier10 - - # définition des frames - self.frame_texte = Frame(self.fenetre) - self.frame_texte.place(relx=0,rely=0,relwidth=1,relheight=0.7) - # définition de la zone texte et du scrollbar - self.zone_texte = Text(self.frame_texte,font=fonte) - self.zone_texte.bind("", self.page_up) - self.zone_texte.bind("", self.page_down) - self.zone_texte.bind("", self.unit_up) - self.zone_texte.bind("", self.unit_down) - self.scroll_v = Scrollbar (self.frame_texte,command = self.zone_texte.yview) - self.scroll_v.pack(side='right',fill ='y') - self.zone_texte.pack(side='top',fill='both',expand=1,padx=5,pady=10) - self.zone_texte.configure(yscrollcommand=self.scroll_v.set) - # affichage du texte - self.affiche_texte(self.texte) - self.zone_texte.config(state="disabled") - - # définition des boutons - self.frame_boutons = Frame(self.fenetre) - self.frame_boutons.place(relheight=0.3,relx=0,rely=0.65,relwidth=1.) - self.label1 = Label(self.frame_boutons,text="surligner la") - self.label2 = Label(self.frame_boutons,text="ligne entière") - self.label1.place(relx=0.1,rely=0) - self.label2.place(relx=0.1,rely=0.5) - self.but_quit = Button(self.frame_boutons,text = "Fermer",command=self.quit) - self.but_save = Button(self.frame_boutons,text = "Choisir",command = self.Choisir) - self.but_save.place(relx=0.6,rely=0,relheight=1) - self.but_quit.place(relx=0.8,rely=0,relheight=1) - - - def Choisir(self): - try: - selection=self.zone_texte.selection_get() - except: - showerror("Pas de donnée sélectionnée", - "Selectionner un parametre") - l_param = "" - for param in selection.splitlines(): - nomparam=param[0:param.find("=")-1] - if nomparam != '' : - l_param=l_param+nomparam+',' - self.parent.entry.delete(0,Tkinter.END) - self.parent.entry.insert(0,l_param[0:-1]) - self.parent.valid_valeur() - self.quit() - -class Formulaire: - """ - Cette classe permet de créer une boîte Dialog dans laquelle - on affiche un formulaire à remplir par l'utilisateur - """ - def __init__(self,fen_pere,obj_pere=None,titre="",texte="",items=(),mode='query',commande=None): - self.resultat=0 - if items in ((),[]) : return - self.items = items - self.titre = titre - self.texte = texte - self.fen_pere = fen_pere - self.obj_pere = obj_pere - self.mode= mode - self.command = commande - self.display() - - def display(self): - self.init_validateurs() - self.init_fenetre() - self.init_texte() - self.init_items_formulaire() - self.fenetre.activate(geometry='centerscreenalways') - - def init_validateurs(self): - """ - Crée le dictionnaire des validateurs des objets reconnus par le formulaire - """ - self.d_validateurs = {} - self.d_validateurs['rep'] = self.repvalidator - self.d_validateurs['file'] = self.filevalidator - self.d_validateurs['cata']= self.catavalidator - self.d_validateurs['mot']= self.motvalidator - self.d_validateurs['mot2']= self.mot2validator - self.d_validateurs['mot3']= self.mot3validator - self.d_validateurs['mot4']= self.mot4validator - - def init_fenetre(self): - """ - Crée la fenêtre Dialog - """ - if self.mode == 'query': - buttons=('Valider','Annuler') - defaultbutton = 'Valider' - elif self.mode == 'display': - if self.command : - buttons=(self.command[0],'OK') - defaultbutton = 'OK' - else: - buttons=('OK') - defaultbutton = 'OK' - self.fenetre = Pmw.Dialog(self.fen_pere, - buttons=buttons, - defaultbutton = defaultbutton, - title = self.titre, - command = self.execute) - self.fenetre.withdraw() - - def init_texte(self): - """ - Crée le label qui affiche le texte à l'intérieur du panneau - """ - fonte=fontes.standard - fr_texte = Frame(self.fenetre.interior(),height=60) - fr_texte.pack(side='top',fill='x',expand=1) - Label(fr_texte,text = self.texte, font=fonte).place(relx=0.5,rely=0.5,anchor='center') - - def init_items_formulaire(self): - """ - Crée et affiche les items dans la boîte de dialogue - """ - self.radiobut = 0 - self.widgets = [] - self.item_widgets = {} - length_maxi = 0 - for item in self.items: - if len(item[0])>length_maxi : length_maxi = len(item[0]) - window = self.fenetre.interior() - for item in self.items : - if len(item) == 4 : - label,nature,nom_var,defaut = item - chaine="Yes" - chaine2="No" - else : - label,nature,nom_var,defaut,chaine,chaine2 = item - - # création de la frame - fr_item = Frame(window,height=40,width=700) - fr_item.pack(side='top',fill='x',expand=1) - # création du label - Label(fr_item,text = label).place(relx=0.05,rely=0.4) - if nature in ('rep','file','cata','mot','mot2','mot3','mot4'): - # création de l'entry - e_item = Entry(fr_item) - e_item.place(relx=0.5,rely=0.4,relwidth=0.45) - self.widgets.append(e_item) - self.item_widgets[item] = e_item - if defaut : e_item.insert(0,str(defaut)) - elif nature == 'YesNo': - # création de la StringVar - var = StringVar() - setattr(self,'item_'+nom_var,var) - var.set(defaut) - # création du radiobouton - rb1 = Radiobutton(fr_item,text=chaine,variable=var,value='OUI') - rb2 = Radiobutton(fr_item,text=chaine2,variable=var,value='NON') - rb1.place(relx=0.65,rely=0.5,anchor='center') - rb2.place(relx=0.80,rely=0.5,anchor='center') - self.widgets.append((rb1,rb2)) - self.item_widgets[item] = var - # détermination de la méthode à appliquer sur les boutons - if self.mode == 'query': - function = self.active - elif self.mode == 'display': - function = self.inactive - else: - return - # on applique la méthode sur les boutons (activation ou désactivation) - for widget in self.widgets : - if type(widget) == types.TupleType: - for widg in widget : - apply(function,(widg,),{}) - else: - apply(function,(widget,),{}) - - def active(self,widget): - """ - Active le widget passé en argument - """ - widget.configure(state='normal',bg='white') - - def inactive(self,widget): - """ - Inactive le widget passé en argument - """ - if not isinstance(widget,Radiobutton) : - widget.configure(state='disabled',bg='gray95') - else : - widget.configure(state='disabled') - -# -------------------------------------------------------------------------------- -# Validateurs des noms de répertoire, de fichiers et de catalogues -# ------------------------------------------------------------------------------- - - def motvalidator(self,text): - text2="("+text+")" - return self.motlongueurvalidator(text2,1) - - def mot2validator(self,text): - return self.motlongueurvalidator(text,2) - - def mot3validator(self,text): - return self.motlongueurvalidator(text,3) - - def mot4validator(self,text): - return self.motlongueurvalidator(text,4) - - def motlongueurvalidator(self,text,longueur): - try : - if ((text[0] != "(") or (text[-1] != ")")) : return 0 - if len(text.split(",")) != longueur : return 0 - return 1 - except : - return 0 - - def repvalidator(self,text): - """ - Teste si text peut faire référence à un répertoire ou non - Retourne 1 si valide, 0 sinon - """ - return os.path.isdir(text),'Répertoire introuvable : %s' %text - - def filevalidator(self,text): - """ - Teste si text peut faire référence à un fichier ou non - Retourne 1 si valide, 0 sinon - """ - return os.path.isfile(text),'Fichier introuvable : %s' %text - - def catavalidator(self,text): - """ - Teste si text est un chemin d'accès valide à un catalogue - Retourne 1 si valide, 0 sinon - """ - return os.path.isfile(text),"Catalogue introuvable : %s" %text - -# -------------------------------------------------------------------------------- -# Méthodes callbacks des boutons et de fin -# -------------------------------------------------------------------------------- - - def execute(self,txt): - """ - Cette commande est activée à chaque clic sur un bouton. - Redirige l'action sur la bonne méthode en fonction du bouton activé - """ - if txt == 'Valider': - self.fini() - elif txt in ('OK','Annuler'): - self.quit() - elif txt == 'Modifier': - self.resultat = apply(self.command[1],(),{}) - self.fenetre.destroy() - else : - print "Nom de bouton inconnu" - self.quit() - - def fini(self): - """ - Commande qui termine le panneau et sauvegarde les nouvelles options - dans l'objet resultat (dictionnaire) - """ - dico={} - for item,widget in self.item_widgets.items(): - nom_var = item[2] - type_var = item[1] - valeur = widget.get() - if self.d_validateurs.has_key(type_var): - test = self.d_validateurs[type_var](valeur) - if not test : - # une entrée n'est pas valide --> on la met en surbrillance et on quitte la méthode - # sans tuer la fenêtre bien sûr - widget.selection_range(0,END) - return - dico[nom_var] = valeur - self.fenetre.destroy() - self.resultat=dico - - def quit(self): - self.fenetre.destroy() - self.resultat=None - -class ListeChoix : - """ Cette classe est utilisée pour afficher une liste de choix passée en paramètre - en passant les commandes à lancer suivant différents bindings """ - def __init__(self,parent,page,liste,liste_commandes=[],liste_marques =[],active ='oui',filtre='non',titre='', - optionReturn=None, fonte_titre=fontes.standard_gras_souligne): - self.parent = parent - self.page = page - self.liste = liste - self.dico_labels={} - self.dico_mots={} - self.nBlabel = 0 - self.dico_place={} - self.dico_mots={} - self.selection = None - self.liste_commandes = liste_commandes - self.liste_marques = liste_marques - self.arg_selected='' - self.active = active - self.titre = titre - self.filtre = filtre - self.optionReturn = optionReturn - self.fonte_titre=fonte_titre - self.init() - - def init(self): - self.make_label_titre() - self.make_entry_filtre() - self.make_text_box() - try: - self.entry.component('entry').focus() - except: - pass - - def make_label_titre(self): - """ Crée le label correspondant au titre """ - if self.titre == '' : return - self.label = Label(self.page, - text = self.titre, - font = self.fonte_titre) - self.label.pack(side='top',pady=2) - - def make_entry_filtre(self): - """ Crée l'entry permettant à l'utilisateur d'entrer un filtre de sélection dans la liste """ - if self.filtre != 'oui' : return - self.entry = Pmw.EntryField(self.page,labelpos='w', - label_text="Filtre :", - command=self.entry_changed) - self.entry.pack(side='top',pady=2) - - def make_text_box(self): - """ Crée la fenêtre texte dans laquelle sera affichée la liste """ - self.MCbox = Text (self.page,relief='sunken',bg='gray95',bd=2) - self.MCscroll = Scrollbar (self.page,command = self.MCbox.yview) - self.MCscroll.pack(side='right',fill ='y',pady=2) - self.MCbox.pack(fill='y',expand=1,padx=2,pady=2) - self.MCbox.configure(yscrollcommand=self.MCscroll.set) - - - def affiche_liste(self): - """ Affiche la liste dans la fenêtre""" - liste_labels=[] - self.MCbox.config(state=NORMAL) - self.MCbox.delete(1.0,END) - self.nBlabel = 0 - self.dico_place={} - for objet in self.liste : - if type(objet) == types.InstanceType: - try: - mot = objet.nom - except: - mot = str(objet) - elif type(objet) in (types.StringType,types.IntType): - mot = objet - elif type(objet) == types.FloatType : - mot = self.parent.get_valeur_texte(objet) - if mot == "" : - mot = str(objet) - elif type(objet) == types.TupleType : - mot="(" - premier=1 - for val in objet: - if (not premier): - mot=mot+"," - else: - premier=0 - valtexte = self.parent.get_valeur_texte(val) - if valtexte != "" : - mot=mot+valtexte - else: - mot=mot+str(val) - mot=mot+")" - elif string.find(str(type(objet)),".SD.") : - mot=objet.nom - else : - mot=`objet` - label = Label(self.MCbox, - text = mot, - fg = 'black',bg = 'gray95',justify = 'left') - self.dico_labels[mot]=label - self.dico_place[mot]=self.nBlabel - self.dico_mots[label]=mot - self.nBlabel=self.nBlabel+1 - liste_labels.append(label) - self.MCbox.window_create(END, - window=label, - stretch = 1) - self.MCbox.insert(END,'\n') - if self.optionReturn != None : - label.bind("",lambda e,s=self,c=self.liste_commandes[2][1],x=objet,l=label : s.chooseitemsurligne(x,l,c)) - label.bind("",lambda e,s=self,c=self.liste_commandes[2][1],x=objet,l=label : s.chooseitemsurligne(x,l,c)) - label.bind("",lambda e,s=self,x=objet,l=label : s.selectNextItem(x,l)) - label.bind("",lambda e, s=self,x=objet,l=label : s.selectNextItem(x,l)) - label.bind("" ,lambda e,s=self,x=objet,l=label : s.selectPrevItem(x,l)) - label.bind("" ,lambda e,s=self,x=objet,l=label : s.selectPrevItem(x,l)) - if self.active == 'oui': - label.bind(self.liste_commandes[0][0],lambda e,s=self,c=self.liste_commandes[0][1],x=objet,l=label : s.selectitem(x,l,c)) - label.bind(self.liste_commandes[1][0],lambda e,s=self,c=self.liste_commandes[1][1],x=objet,l=label : s.deselectitem(l,x,c)) - label.bind(self.liste_commandes[2][0],lambda e,s=self,c=self.liste_commandes[2][1],x=objet,l=label : s.chooseitem(x,l,c)) - - for marque in self.liste_marques: - try: - self.markitem(liste_labels[marque]) - except: - pass - - self.MCbox.config(state=DISABLED) - self.selection = None - self.dontselect=0 - for event,callback in self.liste_commandes: - if event == "": - self.selection=None,None,callback - break - - def clear_marque(self): - try: - self.dico_labels[self.arg_selected].configure(bg='gray95',fg='black') - self.arg_selected = '' - except : - pass - - def surligne(self,marque): - try : - self.highlightitem(self.dico_labels[marque]) - self.arg_selected = marque - except: - pass - - def chooseitemsurligne(self,mot,label,commande): - """ Active la méthode de choix passée en argument""" - try: - mot=self.arg_selected - commande(mot) - except AsException,e: - raison=str(e) - showerror(raison.split('\n')[0],raison) - - def chooseitem(self,mot,label,commande): - """ Active la méthode de choix passée en argument""" - try: - commande(mot) - except AsException,e: - raison=str(e) - showerror(raison.split('\n')[0],raison) - - def afficheMot(self,mot): - """ Pour contourner le bug sur l index - on commence par la methode dite normale - puis par la methode de contournement - puis rien du tout - """ - try: - labelsuivant=self.dico_labels[mot] - index = self.MCbox.index(labelsuivant) - self.MCbox.see(index) - except : - posmot=self.dico_place[mot] - totale=self.nBlabel + 0.0 - self.MCbox.yview_moveto(posmot/totale) - - def selectNextItem(self,mot,label): - index=self.liste.index(mot) - indexsuivant=index+1 - if indexsuivant > len(self.liste) -1: - indexsuivant=0 - motsuivant=self.liste[indexsuivant] - labelsuivant=self.dico_labels[motsuivant] - self.afficheMot(motsuivant) - self.selectthis(motsuivant,labelsuivant,self.selection[2],) - self.dontselect=1 - - def selectPrevItem(self,mot,label): - index=self.liste.index(mot) - indexprec=index-1 - motprec=self.liste[indexprec] - labelprec=self.dico_labels[motprec] - self.afficheMot(motprec) - self.selectthis(motprec,labelprec,self.selection[2],) - self.dontselect=1 - - def selectthis(self,mot,label,commande) : - self.clear_marque() - if self.selection != None : - self.deselectitem(self.selection[1],self.selection[0],self.selection[2],) - self.highlightitem(label) - self.selection = (mot,label,commande) - self.arg_selected = mot - if commande : commande(mot) - - def selectitem(self,mot,label,commande) : - """ Met l'item sélectionné (représenté par son label) en surbrillance - et lance la commande associée au double-clic""" - if self.dontselect: - self.dontselect=0 - return - self.selectthis(mot,label,commande) - - def highlightitem(self,label) : - """ Met l'item représenté par son label en surbrillance """ - label.focus_set() - label.configure(bg='#00008b',fg='white') - - def markitem(self,label): - """ Met l'item (représenté par son label) en rouge """ - label.configure(bg='gray95',fg='red') - - def deselectitem(self,label,mot='',commande=None) : - """ Remet l'item (représenté par son label) en noir""" - if label:label.configure(bg='gray95',fg='black') - self.arg_selected = '' - if commande and mot : commande(mot) - - def cherche_selected_item(self): - try : - index=self.MCbox.index(self.selection[1]) - lign,col=map(int,string.split(index,'.')) - except : - label=self.dico_labels[self.arg_selected] - mot=self.dico_mots[label] - lign=self.dico_place[mot]+1 - return lign - - def remove_selected_item(self): - try : - index=self.MCbox.index(self.selection[1]) - lign,col=map(int,string.split(index,'.')) - except : - label=self.dico_labels[self.arg_selected] - mot=self.dico_mots[label] - lign=self.dico_place[mot]+1 - del self.liste[lign-1] - self.affiche_liste() - - def entry_changed(self,event=None): - """ Cette méthode est invoquée chaque fois que l'utilisateur modifie le contenu - de l'entry et frappe """ - if self.arg_selected != '' : self.deselectitem(self.dico_labels[self.arg_selected]) - filtre = self.entry.get()+"*" - FILTRE = string.upper(filtre) - self.dontselect=0 - for arg in self.liste : - if fnmatch.fnmatch(arg,filtre) or fnmatch.fnmatch(arg,FILTRE) : - label=self.dico_labels[arg] - self.afficheMot(arg) - self.selectitem(arg,label,self.selection[2]) - break - - #try : - #self.dico_labels[self.arg_selected].focus_set() - #except : - #pass - - - # PN attention à la gestion des paramétres - # cela retourne H = 1 , et ni H, ni 1 - # print repr(val) - # print val.__class__.__name__ - def get_liste(self): - l=[] - for val in self.liste: -# try: -# v = eval(val) -# l.append(v) -# except: - l.append(val) - return l - - def put_liste(self,liste): - self.liste = liste - self.affiche_liste() - -class Affichage : - """ Cette classe permet d'afficher au lancement d'EFICAS le message - d'attente et la barre de progression""" - def __init__(self,master,message,barre ='oui'): - from Tools.foztools.foztools import Slider - fonte=fontes.standard12_gras - self.master=master - self.frame = Frame(self.master) - self.frame.pack(expand=1,fill='both') - self.mess = Label(self.frame,text=message,justify='center', - bd=2,relief='groove',font=fonte) - self.mess.pack(in_ = self.frame,side='top',expand=1,fill='both') - self.progress = Slider(self.frame,value=0,max=100,orientation='horizontal', - fillColor='#00008b',width=200,height=30, - background='white',labelColor='red') - if barre == 'oui': - self.progress.frame.pack(in_=self.frame,side='top') - self.master.update() - if barre == 'oui': - self.progress.frame.after(1000,self.update) - - def configure(self,**options): - if options.has_key('message'): - self.mess.configure(text=options['message']) - if options.has_key('barre'): - if options['barre'] == 'oui' : - self.progress.frame.pack(in_=self.frame,side='top') - elif options['barre'] == 'non' : - self.progress.frame.pack_forget() - self.master.update_idletasks() - - def quit(self): - self.frame.destroy() - self.master.update() - - def update(self,event=None): - """ Permet de faire avancer la barre de progression """ - try : - bar=self.progress - bar.value = bar.value+self.increment - bar.update() - self.master.after(100,self.update) - except: - pass - - def configure_barre(self,nb): - """ Calcule l'incrément de progression de la barre en fonction - du nombre d'opérations à effectuer afin que le compteur - soit à 100% à la fin des opérations""" - self.increment = 100./nb - self.progress.update() - -class Ask_Format_Fichier : - """ - Cette classe permet de créer une fenêtre Toplevel dans laquelle - on propose le choix du format de fichier de commandes à ouvrir - """ - def __init__(self,appli): - self.fenetre = Toplevel() - self.fenetre.configure(width = 250,height=150) - self.fenetre.protocol("WM_DELETE_WINDOW", self.quit) - self.fenetre.title("Choix du format du fichier de commandes") - # définition des frames - self.frame_texte = Frame(self.fenetre) - self.frame_radioboutons = Frame(self.fenetre) - self.frame_bouton_ok = Frame(self.fenetre) - self.frame_texte.place(relx=0,rely=0,relwidth=1,relheight=0.3) - self.frame_radioboutons.place(relheight=0.5,relx=0,rely=0.3,relwidth=1.) - self.frame_bouton_ok.place(relheight=0.2,relx=0,rely=0.8,relwidth=1.) - # définition de la zone texte et du scrollbar - zone_texte = Label(self.frame_texte,text = "Format du fichier à ouvrir :") - zone_texte.pack(side='top',fill='both',expand=1,padx=5,pady=10) - # définition des radioboutons - Radiobutton(self.frame_radioboutons,text='Format Aster (Code_Aster --> v5)', - variable=appli.format_fichier,value='Aster').pack(anchor='n') - Radiobutton(self.frame_radioboutons,text='Format Python (Code_Aster v6-->)', - variable=appli.format_fichier,value='Python').pack(anchor='n') - # création du bouton OK - Button(self.frame_bouton_ok,text='OK',command=self.quit).pack(anchor='n') - # centrage de la fenêtre - centerwindow(self.fenetre) - - def quit(self): - self.fenetre.destroy() - -class BARRE_K2000(Toplevel): - def __init__(self,master=None,text = ""): - Toplevel.__init__(self,master,relief='groove') - self.master.iconify() - self.geometry("250x100+0+0") - self.protocol("WM_DELETE_WINDOW",self.quit) - # frame principale dans self (= Toplevel) - self.frame = Frame(self) - self.frame.place(relwidth=1,relheight=1) - # frame contenant le texte à afficher - self.frame_text = Frame(self.frame) - self.frame_text.place(relwidth=1,relheight=0.75,rely=0) - # frame contenant le canvas de la barre - self.frame_canv = Frame(self.frame) - self.frame_canv.place(relwidth=1,relheight=0.25,rely=0.75) - # canvas dans lequel sera affichée la barre K2000 - self.canvas = Canvas(self.frame_canv) - self.canvas.place(relx=0.5,rely=0.5,relheight=0.8,relwidth=0.8,anchor='center') - # on affiche le texte et la barre - self.build_text(text) - self.build_batons() - #self.overrideredirect(1) - # on active la barre ... - self.master.after(1000,self.launch) - # on centre la fenêtre - centerwindow(self) - self.focus() - - def build_text(self,text): - """ - Affichage de text dans frame_text - """ - self.texte_var = StringVar() - self.texte_var.set(text) - Label(self.frame_text,textvariable=self.texte_var).place(relx=0.5,rely=0.5,anchor='center') - - def build_batons(self): - """ - Construit la suite de bâtons dans le canvas - """ - self.l_batons=[] - self.black = -1 - self.sens = 'D' - self.quit = 0 - for i in range(0,40): - id = self.canvas.create_rectangle(i*5,0,(i+1)*5,20,fill='gray90',outline='') - self.l_batons.append(id) - - def launch(self): - """ - Active la barre K2000 en affichant les bâtons avec des couleurs en dégradé - """ - if self.quit == 1 : - self.destroy() - self.master.deiconify() - return - if self.sens == 'D': - self.black = self.black+1 - l_bat = self.l_batons[0:self.black+1] - l_bat.reverse() - elif self.sens == 'G': - self.black = self.black-1 - l_bat = self.l_batons[self.black:] - i=0 - for bat in l_bat : - num_color = 5+i*10 - if num_color < 10 : color = 'black' - elif num_color > 90 : color = 'white' - else: color = 'gray'+`num_color` - self.canvas.itemconfigure(bat,fill=color) - i=i+1 - if self.black == len(self.l_batons) : - self.sens = 'G' - if self.black == 0 and self.sens == 'G':self.sens = 'D' - self.after(80,self.launch) - - def update_text(self,new_text): - """ - Remplace le texte affiché par new_text - """ - self.texte_var.set(new_text) - - def quit(self): - self.quit = 1 - -class ListeChoixParGroupes(ListeChoix) : - """ - Cette classe est utilisée pour afficher une liste de commandes classées par - groupes. L'utilisateur peut réaliser des actions de selection - qui déclenchent des actions spécifiées par les bindings contenus dans liste_commandes - Exemple de binding: - liste_commandes = (("",self.selectCmd), - ("",self.deselectCmd), - ("",self.defCmd)) - Il s'agit d'une liste de doublets dont le premier element est un evenement et le - deuxieme un callback a appeler sur l'evenement en question. - - """ - def __init__(self,parent,page,liste_groupes,dict_groupes,liste_commandes=[],liste_marques =[], - active ='oui',filtre='non',titre='',optionReturn=None,fonte_titre=fontes.standard_gras_souligne): - self.parent = parent - self.page = page - self.liste_groupes = liste_groupes - self.dict_groupes = dict_groupes - self.dico_labels={} - self.selection = None - self.liste_commandes = liste_commandes - self.liste_marques = liste_marques - self.arg_selected='' - self.active = active - self.titre = titre - self.filtre = filtre - self.optionReturn = optionReturn - self.fonte_titre=fonte_titre - self.init() - - def affiche_liste(self): - """ Affiche la liste dans la fenêtre""" - liste_labels=[] - self.dico_mots={} - self.MCbox.config(state=NORMAL) - self.MCbox.delete(1.0,END) - for grp in self.liste_groupes: - # On itère sur les groupes - if grp == "CACHE":continue - liste_commandes=self.dict_groupes[grp] - text="GROUPE<<<<<<<< "+grp+" " - text=text+">"*max(0,30-len(text)) - label = Label(self.MCbox, - text = text, - fg = 'black',bg = 'gray95',justify = 'left') - # On stocke la relation entre le nom de la commande et le label - self.dico_labels[grp]=label - liste_labels.append(label) - self.MCbox.window_create(END, - window=label, - stretch = 1) - self.MCbox.insert(END,'\n') - for cmd in liste_commandes: - label = Label(self.MCbox, - text = cmd, - fg = 'black',bg = 'gray95',justify = 'left') - # On stocke la relation entre le nom de la commande et le label - self.dico_labels[cmd]=label - self.dico_mots[label]=cmd - self.MCbox.window_create(END, - window=label, - stretch = 1) - self.MCbox.insert(END,'\n') - - def null(*tp,**args): return - - if self.active == 'oui': - # Traitement par defaut des evenements - label.bind("",lambda e,s=self,c=null,x=cmd,l=label: s.selectitem(x,l,c)) - label.bind("",lambda e,s=self,c=null,x=cmd,l=label: s.deselectitem(l,x,c)) - label.bind("",lambda e,s=self,c=null,x=cmd,l=label: s.chooseitem(x,l,c)) - label.bind("",lambda e,s=self,c=null,x=cmd,l=label: s.chooseitem(x,l,c)) - label.bind("",lambda e,s=self,c=null,x=cmd,l=label: s.chooseitem(x,l,c)) - label.bind("",lambda e,s=self,c=null,x=cmd,l=label,gr=grp: s.selectNextItem(x,l,c,gr,x)) - label.bind("",lambda e,s=self,c=null,x=cmd,l=label,gr=grp: s.selectNextItem(x,l,c,gr,x)) - label.bind("",lambda e,s=self,c=null,x=cmd,l=label,gr=grp: s.selectPrevItem(x,l,c,gr,x)) - label.bind("",lambda e,s=self,c=null,x=cmd,l=label,gr=grp: s.selectPrevItem(x,l,c,gr,x)) - - # Si des callbacks sont definis on les utilise - for event,callback in self.liste_commandes: - if event == "": - label.bind("",lambda e,s=self,c=callback,x=cmd,l=label: s.selectitem(x,l,c)) - elif event == "": - label.bind("",lambda e,s=self,c=callback,x=cmd,l=label: s.deselectitem(l,x,c)) - elif event == "": - label.bind("",lambda e,s=self,c=callback,x=cmd,l=label: s.chooseitem(x,l,c)) - elif event == "": - label.bind("",lambda e,s=self,c=callback,x=cmd,l=label: s.chooseitem(x,l,c)) - elif event == "": - label.bind("",lambda e,s=self,c=callback,x=cmd,l=label: s.chooseitem(x,l,c)) - elif event == "": - label.bind("",lambda e,s=self,c=callback,x=cmd,l=label,gr=grp:s.selectNextItem(x,l,c,gr,x)) - elif event == "": - label.bind("",lambda e,s=self,c=callback,x=cmd,l=label,gr=grp:s.selectNextItem(x,l,c,gr,x)) - elif event == "": - label.bind("",lambda e,s=self,c=callback,x=cmd,l=label,gr=grp:s.selectPrevItem(x,l,c,gr,x)) - elif event == "": - label.bind("",lambda e,s=self,c=callback,x=cmd,l=label,gr=grp:s.selectPrevItem(x,l,c,gr,x)) - else: - label.bind(event,lambda e,s=self,c=callback,x=cmd,l=label: c()) - - for marque in self.liste_marques: - try: - self.markitem(liste_labels[marque]) - except: - pass - - self.MCbox.config(state=DISABLED) - self.selection = None - self.dontselect=0 - for event,callback in self.liste_commandes: - if event == "": - self.selection=None,None,callback - break - - def selectPrevItem(self,mot,label,callback,group,cmd): - g=self.liste_groupes.index(group) - liste_commandes=self.dict_groupes[group] - c=liste_commandes.index(cmd) - if c > 0: - co=liste_commandes[c-1] - else: - # debut de liste. On passe au groupe precedent - if g > 0: - gr=self.liste_groupes[g-1] - co=self.dict_groupes[gr][-1] - else: - # debut des groupes. On ne fait rien - return - # On a trouve l'item precedent - labelsuivant=self.dico_labels[co] - index = self.MCbox.index(labelsuivant) - self.MCbox.see(index) - self.selectthis(co,labelsuivant,self.selection[2],) - self.dontselect=1 - - def selectNextItem(self,mot,label,callback,group,cmd): - g=self.liste_groupes.index(group) - liste_commandes=self.dict_groupes[group] - c=liste_commandes.index(cmd) - try: - co=liste_commandes[c+1] - except: - # fin de liste. On passe au groupe suivant - try: - gr=self.liste_groupes[g+1] - co=self.dict_groupes[gr][0] - except: - # fin des groupes. On ne fait rien - return - # On a trouve l'item suivant - labelsuivant=self.dico_labels[co] - index = self.MCbox.index(labelsuivant) - self.MCbox.see(index) - self.selectthis(co,labelsuivant,self.selection[2],) - self.dontselect=1 - - def entry_changed(self,event=None): - """ - Cette méthode est invoquée chaque fois que l'utilisateur modifie le contenu - de l'entry et frappe - """ - if self.arg_selected != '' : self.deselectitem(self.dico_labels[self.arg_selected]) - - filtre = self.entry.get()+"*" - FILTRE = string.upper(filtre) - # - # On cherche d'abord dans les noms de groupe - # puis dans les noms de commande groupe par groupe - # - for grp in self.liste_groupes: - if fnmatch.fnmatch(grp,filtre) or fnmatch.fnmatch(grp,FILTRE) : - cmd=self.dict_groupes[grp][0] - label=self.dico_labels[cmd] - index = self.MCbox.index(label) - self.MCbox.see(index) - self.selectitem(cmd,label,self.selection[2]) - # On a trouve un groupe on arrete la recherche - return - - for grp in self.liste_groupes: - for cmd in self.dict_groupes[grp] : - if fnmatch.fnmatch(cmd,filtre) or fnmatch.fnmatch(cmd,FILTRE) : - label=self.dico_labels[cmd] - index = self.MCbox.index(label) - self.MCbox.see(index) - self.selectitem(cmd,label,self.selection[2]) - # On a trouve une commande on arrete la recherche - return - diff --git a/Pmw/Alpha_99_9_example/__init__.py b/Pmw/Alpha_99_9_example/__init__.py deleted file mode 100644 index 83d04e76..00000000 --- a/Pmw/Alpha_99_9_example/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# File to allow this directory to be treated as a python package. diff --git a/Pmw/Alpha_99_9_example/lib/Pmw.def b/Pmw/Alpha_99_9_example/lib/Pmw.def deleted file mode 100644 index 358a2b46..00000000 --- a/Pmw/Alpha_99_9_example/lib/Pmw.def +++ /dev/null @@ -1,9 +0,0 @@ -# Widgets whose name is the same as its module. -_widgets = ('AlphaExample',) - -# Widgets whose name is not the same as its module. -_extraWidgets = {} - -_functions = {} - -_modules = () diff --git a/Pmw/Alpha_99_9_example/lib/PmwAlphaExample.py b/Pmw/Alpha_99_9_example/lib/PmwAlphaExample.py deleted file mode 100644 index 5e4f88c1..00000000 --- a/Pmw/Alpha_99_9_example/lib/PmwAlphaExample.py +++ /dev/null @@ -1,24 +0,0 @@ -import string -import Pmw - -_default_text = "AlphaExample example alpha Pmw megawidget.\nPmw version: " + \ - Pmw.version() + '\nPmw Alpha versions: ' + \ - string.join(Pmw.version(alpha = 1), ' ') - -class AlphaExample(Pmw.MessageDialog): - # Dummy widget for illustrating use of Pmw alpha version directory - - def __init__(self, parent = None, **kw): - - # Define the megawidget options. - INITOPT = Pmw.INITOPT - optiondefs = ( - ('message_text', _default_text, None), - ) - self.defineoptions(kw, optiondefs) - - # Initialise the base class (after defining the options). - Pmw.MessageDialog.__init__(self, parent) - - # Check keywords and initialise options. - self.initialiseoptions(AlphaExample) diff --git a/Pmw/Alpha_99_9_example/lib/__init__.py b/Pmw/Alpha_99_9_example/lib/__init__.py deleted file mode 100644 index 83d04e76..00000000 --- a/Pmw/Alpha_99_9_example/lib/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# File to allow this directory to be treated as a python package. diff --git a/Pmw/Pmw_1_2/__init__.py b/Pmw/Pmw_1_2/__init__.py deleted file mode 100644 index 83d04e76..00000000 --- a/Pmw/Pmw_1_2/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# File to allow this directory to be treated as a python package. diff --git a/Pmw/Pmw_1_2/bin/bundlepmw.py b/Pmw/Pmw_1_2/bin/bundlepmw.py deleted file mode 100755 index fdb7dc00..00000000 --- a/Pmw/Pmw_1_2/bin/bundlepmw.py +++ /dev/null @@ -1,169 +0,0 @@ -#!/usr/bin/env python - -# Helper script when freezing Pmw applications. It concatenates all -# Pmw megawidget files into a single file, 'Pmw.py', in the current -# directory. The script must be called with one argument, being the -# path to the 'lib' directory of the required version of Pmw. -# To freeze a Pmw application, you will also need to copy the -# following files to the application directory before freezing: -# -# PmwBlt.py PmwColor.py - -import os -import regsub -import string -import sys - -# The order of these files is significant. Files which reference -# other files must appear later. Files may be deleted if they are not -# used. -files = [ - 'Dialog', 'TimeFuncs', 'Balloon', 'ButtonBox', 'EntryField', - 'Group', 'LabeledWidget', 'MainMenuBar', 'MenuBar', 'MessageBar', - 'MessageDialog', 'NoteBook', 'OptionMenu', 'PanedWidget', 'PromptDialog', - 'RadioSelect', 'ScrolledCanvas', 'ScrolledField', 'ScrolledFrame', - 'ScrolledListBox', 'ScrolledText', 'HistoryText', 'SelectionDialog', - 'TextDialog', 'TimeCounter', 'AboutDialog', 'ComboBox', 'ComboBoxDialog', - 'Counter', 'CounterDialog', -] - -# Set this to 0 if you do not use any of the Pmw.Color functions: -needColor = 1 - -# Set this to 0 if you do not use any of the Pmw.Blt functions: -needBlt = 1 - -def expandLinks(path): - if not os.path.isabs(path): - path = os.path.join(os.getcwd(), path) - while 1: - if not os.path.islink(path): - break - dir = os.path.dirname(path) - path = os.path.join(dir, os.readlink(path)) - - return path - -def mungeFile(file): - # Read the file and modify it so that it can be bundled with the - # other Pmw files. - file = 'Pmw' + file + '.py' - text = open(os.path.join(srcdir, file)).read() - text = regsub.gsub('import Pmw\>', '', text) - text = regsub.gsub('INITOPT = Pmw.INITOPT', '', text) - text = regsub.gsub('\ -# -# Copyright 2001 MontaVista Software Inc. -# -# This program is free software; you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by the -# Free Software Foundation; either version 2 of the License, or (at your -# option) any later version. -# -# THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED -# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN -# NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, -# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT -# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# -# You should have received a copy of the GNU General Public License along -# with this program; if not, write to the Free Software Foundation, Inc., -# 675 Mass Ave, Cambridge, MA 02139, USA. -# - - -import os -import Tkinter -import Pmw - - -class DirBrowserDialog(Pmw.MegaToplevel): - def __init__(self, parent = None, **kw): - cwd = os.getcwd() - # Define the megawidget options. - INITOPT = Pmw.INITOPT - optiondefs = ( - ('path', cwd, None), - ('hidedotfiles', 1, INITOPT), - ('label', None, INITOPT), - #('labelmargin', 0, INITOPT), - #('labelpos', None, INITOPT), - ('borderx', 20, INITOPT), - ('bordery', 20, INITOPT), - ) - - self.defineoptions(kw, optiondefs) - - # Initialise the base class (after defining the options). - Pmw.MegaToplevel.__init__(self, parent) - - interior = self.interior() - - self.childframe = self.createcomponent('childframe', (), None, - Tkinter.Frame, - (interior,), - borderwidth = 1, - relief = 'raised', - ) - self.childframe.pack(expand = 1, - fill = 'both', - ) - - self.labelframe = self.createcomponent('labelframe', (), None, - Tkinter.Frame, - (self.childframe,), - borderwidth = 2, - relief = 'groove', - ) - self.labelframe.pack(padx = 10, pady = 10, expand = 1, fill = 'both') - - if self['label']: - self.label = self.createcomponent('label', (), None, - Tkinter.Label, - (self.childframe,), - text = self['label'], - ) - self.label.place(x = (10 + self['borderx']), y = 10, anchor = 'w') - - - self.workframe = self.createcomponent('workframe', (), None, - Tkinter.Frame, - (self.labelframe,), - #borderwidth = 2, - #relief = 'groove', - ) - self.workframe.pack(padx = self['borderx'], - pady = self['bordery'], - expand = 1, - fill = 'both', - ) - - self.buttonframe = self.createcomponent('buttonframe', (), None, - Tkinter.Frame, - (interior,), - borderwidth = 1, - relief = 'raised', - ) - self.buttonframe.pack(expand = 0, - fill = 'x', - ) - - self.optbox = self.createcomponent('optbox', (), None, - Pmw.OptionMenu, - (self.workframe,), - command = self.setpath, - ) - self.optbox.bind('', self._setMinimumSize) - - self.listbox = self.createcomponent('listbox', (), None, - Pmw.ScrolledListBox, - (self.workframe,), - dblclickcommand = self._select, - ) - - path = self['path'] - self.entry = self.createcomponent('entryfield', (), None, - Pmw.EntryField, - (self.workframe,), - value = path, - command = self.enteredpath, - labelpos = 'nw', - label_text = 'Current Path:', - ) - - #self.createlabel(self.workframe, childCols = 1, childRows = 3) - - self.buttonbox = self.createcomponent('buttonbox', (), None, - Pmw.ButtonBox, - (self.buttonframe,), - ) - self.buttonbox.add('OK', text = 'OK', - command = self.okbutton) - self.buttonbox.add('Cancel', text = 'Cancel', - command = self.cancelbutton) - self.buttonbox.add('New Directory', text = 'New Directory', - command = self.newdirbutton) - - self.buttonbox.alignbuttons() - self.buttonbox.pack(expand = 1, fill = 'x') - - self.optbox.grid(row = 2, column = 2, sticky = 'ew') - self.listbox.grid(row = 3, column = 2, sticky = 'news') - self.entry.grid(row = 5, column = 2, sticky = 'ew') - self.workframe.grid_rowconfigure(3, weight = 1) - self.workframe.grid_rowconfigure(4, minsize = 20) - self.workframe.grid_columnconfigure(2, weight = 1) - - - self.setpath(self['path']) - - # Check keywords and initialise options. - self.initialiseoptions() - - def setpath(self, path): - path = os.path.abspath(os.path.expanduser(path)) - - if os.path.isfile(path): - path = os.path.dirname(path) - - dirlist = [] - hidedotfiles = self['hidedotfiles'] - try: - posix = (os.name == 'posix') - for entry in os.listdir(path): - entryPath = path + '/' + entry - if hidedotfiles and entry[0] == '.': - # skip dot files if desired - continue - if not os.path.isdir(entryPath): - # skip files - continue - if not os.access(entryPath, os.R_OK | os.X_OK): - # skip directories we can't enter any way - continue - dirlist.append(entry) - - except: - self.entry.setentry(self['path']) - return - - self.entry.setentry(path) - - self['path'] = path - - dirlist.sort() - if path != '/': - dirlist.insert(0, '..') - - self.listbox.setlist(dirlist) - pathlist = [] - while path != '/': - pathlist.append(path) - path = os.path.dirname(path) - pathlist.append('/') - self.optbox.setitems(pathlist, 0) - - def _setMinimumSize(self, event): - # If the optionmenu changes width, make sure it does not - # shrink later. - owidth = self.optbox.winfo_width() - self.workframe.grid_columnconfigure(2, minsize = owidth) - - def _select(self): - sel = self.listbox.getcurselection() - if self['path'] == '/': - self['path'] = '' - if len(sel) > 0: - if sel[0] == '..': - self.setpath(os.path.dirname(self['path'])) - else: - self.setpath(self['path'] + '/' + sel[0]) - - - def getcurpath(self): - return self['path'] - - def enteredpath(self): - self.setpath(self.entry.get()) - - def okbutton(self): - self.deactivate(self['path']) - - def cancelbutton(self): - self.deactivate(None) - - def newdirbutton(self): - CreateDirectoryPopup(self.interior(), self['path']) - self.setpath(self['path']) - - - -class CreateDirectoryPopup: - def __init__(self, parent, path): - self.path = path - self.parent = parent - self.newdirpopup = Pmw.PromptDialog(parent, - buttons = ('OK', 'Cancel'), - defaultbutton = 'OK', - title = 'New Directory', - entryfield_labelpos = 'nw', - label_text = 'Enter new directory name for:\n%s'%self.path, - command = self._buttonpress - ) - - self.newdirpopup.activate() - - def _buttonpress(self, button): - if button == 'OK': - newdirname = self.newdirpopup.get() - dirlist = os.listdir(self.path) - if newdirname in dirlist: - ErrorPopup(self.parent, - 'Error: "%s", already exists as a file or directory.'%newdirname) - else: - try: - os.mkdir(self.path + '/' + newdirname) - except: - ErrorPopup(self.parent, - 'Error: Could not create directory: "%s"'%newdirname) - else: - self.newdirpopup.deactivate() - else: - self.newdirpopup.deactivate() - - -def ErrorPopup(parent, message): - error = Pmw.MessageDialog(parent, title = 'Error', - message_text = message, - defaultbutton = 0, - ) - error.activate() - -if __name__ == '__main__': - - rootWin = Tkinter.Tk() - - Pmw.initialise() - - rootWin.title('Directory Browser Dialog Demo') - - def buildBrowser(): - # Create the hierarchical directory browser widget - dirBrowserDialog = DirBrowserDialog(rootWin, - #labelpos = 'nw', - label = 'Select a directory', - title = 'Directory Selector', - #path = '~', - #hidedotfiles = 0, - ) - dir = dirBrowserDialog.activate() - print 'Selected Directory:', dir - - dirButton = Tkinter.Button(rootWin, text="Browser", command=buildBrowser) - dirButton.pack(side = 'left', padx = 10, pady = 10) - - exitButton = Tkinter.Button(rootWin, text="Quit", command=rootWin.quit) - exitButton.pack(side = 'left', padx = 10, pady = 10) - - rootWin.mainloop() diff --git a/Pmw/Pmw_1_2/contrib/MCListbox.py b/Pmw/Pmw_1_2/contrib/MCListbox.py deleted file mode 100644 index 166b8a04..00000000 --- a/Pmw/Pmw_1_2/contrib/MCListbox.py +++ /dev/null @@ -1,706 +0,0 @@ -# -# FILE: MCListbox.py -# -# DESCRIPTION: -# This file provides a generic Multi-Column Listbox widget. It is derived -# from a heavily hacked version of Pmw.ScrolledFrame -# -# This program is free software; you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by the -# Free Software Foundation; either version 2 of the License, or (at your -# option) any later version. -# -# THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED -# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN -# NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, -# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT -# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# -# You should have received a copy of the GNU General Public License along -# with this program; if not, write to the Free Software Foundation, Inc., -# 675 Mass Ave, Cambridge, MA 02139, USA. -# - -import string -import Tkinter -import Pmw - -class MultiColumnListbox(Pmw.MegaWidget): - def __init__(self, parent = None, **kw): - colors = Pmw.Color.getdefaultpalette(parent) - - # Define the megawidget options. - INITOPT = Pmw.INITOPT - optiondefs = ( - #('borderframe', 1, INITOPT), - ('horizflex', 'fixed', self._horizflex), - ('horizfraction', 0.05, INITOPT), - ('hscrollmode', 'dynamic', self._hscrollMode), - ('labelmargin', 0, INITOPT), - ('labelpos', None, INITOPT), - ('scrollmargin', 2, INITOPT), - ('usehullsize', 0, INITOPT), - ('vertflex', 'fixed', self._vertflex), - ('vertfraction', 0.05, INITOPT), - ('vscrollmode', 'dynamic', self._vscrollMode), - ('labellist', None, INITOPT), - ('selectbackground', colors['selectBackground'], INITOPT), - ('selectforeground', colors['selectForeground'], INITOPT), - ('background', colors['background'], INITOPT), - ('foreground', colors['foreground'], INITOPT), - ('command', None, None), - ('dblclickcommand', None, None), - ) - self.defineoptions(kw, optiondefs) - - # Initialise the base class (after defining the options). - Pmw.MegaWidget.__init__(self, parent) - - self._numcolumns = len(self['labellist']) - self._columnlabels = self['labellist'] - self._lineid = 0 - self._numrows = 0 - self._lineitemframes = [] - self._lineitems = [] - self._lineitemdata = {} - self._labelframe = {} - self._cursel = [] - - # Create the components. - self.origInterior = Pmw.MegaWidget.interior(self) - - if self['usehullsize']: - self.origInterior.grid_propagate(0) - - # Create a frame widget to act as the border of the clipper. - self._borderframe = self.createcomponent('borderframe', - (), None, - Tkinter.Frame, - (self.origInterior,), - relief = 'sunken', - borderwidth = 2, - ) - self._borderframe.grid(row = 2, column = 2, - rowspan = 2, sticky = 'news') - - # Create the clipping windows. - self._hclipper = self.createcomponent('hclipper', - (), None, - Tkinter.Frame, - (self._borderframe,), - width = 400, - height = 300, - ) - self._hclipper.pack(fill = 'both', expand = 1) - - self._hsframe = self.createcomponent('hsframe', (), None, - Tkinter.Frame, - (self._hclipper,), - ) - - - self._vclipper = self.createcomponent('vclipper', - (), None, - Tkinter.Frame, - (self._hsframe,), - #width = 400, - #height = 300, - highlightthickness = 0, - borderwidth = 0, - ) - - self._vclipper.grid(row = 1, column = 0, - columnspan = self._numcolumns, - sticky = 'news')#, expand = 1) - self._hsframe.grid_rowconfigure(1, weight = 1)#, minsize = 300) - - - gridcolumn = 0 - for labeltext in self._columnlabels: - lframe = self.createcomponent(labeltext+'frame', (), None, - Tkinter.Frame, - (self._hsframe,), - borderwidth = 1, - relief = 'raised', - ) - label = self.createcomponent(labeltext, (), None, - Tkinter.Label, - (lframe,), - text = labeltext, - ) - label.pack(expand = 0, fill = 'y', side = 'left') - lframe.grid(row = 0, column = gridcolumn, sticky = 'ews') - self._labelframe[labeltext] = lframe - #lframe.update() - #print lframe.winfo_reqwidth() - self._hsframe.grid_columnconfigure(gridcolumn, weight = 1) - gridcolumn = gridcolumn + 1 - - lframe.update() - self._labelheight = lframe.winfo_reqheight() - self.origInterior.grid_rowconfigure(2, minsize = self._labelheight + 2) - - self.origInterior.grid_rowconfigure(3, weight = 1, minsize = 0) - self.origInterior.grid_columnconfigure(2, weight = 1, minsize = 0) - - # Create the horizontal scrollbar - self._horizScrollbar = self.createcomponent('horizscrollbar', - (), 'Scrollbar', - Tkinter.Scrollbar, - (self.origInterior,), - orient='horizontal', - command=self._xview - ) - - # Create the vertical scrollbar - self._vertScrollbar = self.createcomponent('vertscrollbar', - (), 'Scrollbar', - Tkinter.Scrollbar, - (self.origInterior,), - #(self._hclipper,), - orient='vertical', - command=self._yview - ) - - self.createlabel(self.origInterior, childCols = 3, childRows = 4) - - # Initialise instance variables. - self._horizScrollbarOn = 0 - self._vertScrollbarOn = 0 - self.scrollTimer = None - self._scrollRecurse = 0 - self._horizScrollbarNeeded = 0 - self._vertScrollbarNeeded = 0 - self.startX = 0 - self.startY = 0 - self._flexoptions = ('fixed', 'expand', 'shrink', 'elastic') - - # Create a frame in the clipper to contain the widgets to be - # scrolled. - self._vsframe = self.createcomponent('vsframe', - (), None, - Tkinter.Frame, - (self._vclipper,), - #height = 300, - #borderwidth = 4, - #relief = 'groove', - ) - - # Whenever the clipping window or scrolled frame change size, - # update the scrollbars. - self._hsframe.bind('', self._reposition) - self._vsframe.bind('', self._reposition) - self._hclipper.bind('', self._reposition) - self._vclipper.bind('', self._reposition) - - #elf._vsframe.bind('', self._vsframeselect) - - # Check keywords and initialise options. - self.initialiseoptions() - - def destroy(self): - if self.scrollTimer is not None: - self.after_cancel(self.scrollTimer) - self.scrollTimer = None - Pmw.MegaWidget.destroy(self) - - # ====================================================================== - - # Public methods. - - def interior(self): - return self._vsframe - - # Set timer to call real reposition method, so that it is not - # called multiple times when many things are reconfigured at the - # same time. - def reposition(self): - if self.scrollTimer is None: - self.scrollTimer = self.after_idle(self._scrollBothNow) - - - - def insertrow(self, index, rowdata): - #if len(rowdata) != self._numcolumns: - # raise ValueError, 'Number of items in rowdata does not match number of columns.' - if index > self._numrows: - index = self._numrows - - rowframes = {} - for columnlabel in self._columnlabels: - celldata = rowdata.get(columnlabel) - cellframe = self.createcomponent(('cellframeid.%d.%s'%(self._lineid, - columnlabel)), - (), ('Cellframerowid.%d'%self._lineid), - Tkinter.Frame, - (self._vsframe,), - background = self['background'], - #borderwidth = 1, - #relief = 'flat' - ) - - cellframe.bind('', self._cellframedblclick) - cellframe.bind('', self._cellframeselect) - - if celldata: - cell = self.createcomponent(('cellid.%d.%s'%(self._lineid, - columnlabel)), - (), ('Cellrowid.%d'%self._lineid), - Tkinter.Label, - (cellframe,), - background = self['background'], - foreground = self['foreground'], - text = celldata, - ) - - cell.bind('', self._celldblclick) - cell.bind('', self._cellselect) - - cell.pack(expand = 0, fill = 'y', side = 'left', padx = 1, pady = 1) - rowframes[columnlabel] = cellframe - - self._lineitemdata[self._lineid] = rowdata - self._lineitems.insert(index, self._lineid) - self._lineitemframes.insert(index, rowframes) - self._numrows = self._numrows + 1 - self._lineid = self._lineid + 1 - - self._placedata(index) - - def _placedata(self, index = 0): - gridy = index - for rowframes in self._lineitemframes[index:]: - gridx = 0 - for columnlabel in self._columnlabels: - rowframes[columnlabel].grid(row = gridy, - column = gridx, - sticky = 'news') - gridx = gridx + 1 - gridy = gridy + 1 - - - - def addrow(self, rowdata): - self.insertrow(self._numrows, rowdata) - - def delrow(self, index): - rowframes = self._lineitemframes.pop(index) - for columnlabel in self._columnlabels: - rowframes[columnlabel].destroy() - self._placedata(index) - self._numrows = self._numrows - 1 - del self._lineitems[index] - if index in self._cursel: - self._cursel.remove(index) - - - def curselection(self): - # Return a tuple of just one element as this will probably be the - # interface used in a future implementation when multiple rows can - # be selected at once. - return tuple(self._cursel) - - def getcurselection(self): - # Return a tuple of just one row as this will probably be the - # interface used in a future implementation when multiple rows can - # be selected at once. - sellist = [] - for sel in self._cursel: - sellist.append(self._lineitemdata[self._lineitems[sel]]) - return tuple(sellist) - - # ====================================================================== - - # Configuration methods. - - def _hscrollMode(self): - # The horizontal scroll mode has been configured. - - mode = self['hscrollmode'] - - - if mode == 'static': - if not self._horizScrollbarOn: - self._toggleHorizScrollbar() - elif mode == 'dynamic': - if self._horizScrollbarNeeded != self._horizScrollbarOn: - self._toggleHorizScrollbar() - elif mode == 'none': - if self._horizScrollbarOn: - self._toggleHorizScrollbar() - else: - message = 'bad hscrollmode option "%s": should be static, dynamic, or none' % mode - raise ValueError, message - - def _vscrollMode(self): - # The vertical scroll mode has been configured. - - mode = self['vscrollmode'] - - if mode == 'static': - if not self._vertScrollbarOn: - self._toggleVertScrollbar() - elif mode == 'dynamic': - if self._vertScrollbarNeeded != self._vertScrollbarOn: - self._toggleVertScrollbar() - elif mode == 'none': - if self._vertScrollbarOn: - self._toggleVertScrollbar() - else: - message = 'bad vscrollmode option "%s": should be static, dynamic, or none' % mode - raise ValueError, message - - def _horizflex(self): - # The horizontal flex mode has been configured. - - flex = self['horizflex'] - - if flex not in self._flexoptions: - message = 'bad horizflex option "%s": should be one of %s' % \ - mode, str(self._flexoptions) - raise ValueError, message - - self.reposition() - - def _vertflex(self): - # The vertical flex mode has been configured. - - flex = self['vertflex'] - - if flex not in self._flexoptions: - message = 'bad vertflex option "%s": should be one of %s' % \ - mode, str(self._flexoptions) - raise ValueError, message - - self.reposition() - - - - # ====================================================================== - - # Private methods. - - def _reposition(self, event): - gridx = 0 - for col in self._columnlabels: - maxwidth = self._labelframe[col].winfo_reqwidth() - for row in self._lineitemframes: - cellwidth = row[col].winfo_reqwidth() - if cellwidth > maxwidth: - maxwidth = cellwidth - self._hsframe.grid_columnconfigure(gridx, minsize = maxwidth) - gridwidth = self._hsframe.grid_bbox(column = gridx, row = 0)[2] - if self['horizflex'] in ('expand', 'elastic') and gridwidth > maxwidth: - maxwidth = gridwidth - self._vsframe.grid_columnconfigure(gridx, minsize = maxwidth) - gridx = gridx + 1 - - - - self._vclipper.configure(height = self._hclipper.winfo_height() - self._labelheight) - - self.reposition() - - # Called when the user clicks in the horizontal scrollbar. - # Calculates new position of frame then calls reposition() to - # update the frame and the scrollbar. - def _xview(self, mode, value, units = None): - - if mode == 'moveto': - frameWidth = self._hsframe.winfo_reqwidth() - self.startX = string.atof(value) * float(frameWidth) - else: - clipperWidth = self._hclipper.winfo_width() - if units == 'units': - jump = int(clipperWidth * self['horizfraction']) - else: - jump = clipperWidth - - if value == '1': - self.startX = self.startX + jump - else: - self.startX = self.startX - jump - - self.reposition() - - # Called when the user clicks in the vertical scrollbar. - # Calculates new position of frame then calls reposition() to - # update the frame and the scrollbar. - def _yview(self, mode, value, units = None): - - if mode == 'moveto': - frameHeight = self._vsframe.winfo_reqheight() - self.startY = string.atof(value) * float(frameHeight) - else: - clipperHeight = self._vclipper.winfo_height() - if units == 'units': - jump = int(clipperHeight * self['vertfraction']) - else: - jump = clipperHeight - - if value == '1': - self.startY = self.startY + jump - else: - self.startY = self.startY - jump - - self.reposition() - - def _getxview(self): - - # Horizontal dimension. - clipperWidth = self._hclipper.winfo_width() - frameWidth = self._hsframe.winfo_reqwidth() - if frameWidth <= clipperWidth: - # The scrolled frame is smaller than the clipping window. - - self.startX = 0 - endScrollX = 1.0 - - if self['horizflex'] in ('expand', 'elastic'): - relwidth = 1 - else: - relwidth = '' - else: - # The scrolled frame is larger than the clipping window. - - if self['horizflex'] in ('shrink', 'elastic'): - self.startX = 0 - endScrollX = 1.0 - relwidth = 1 - else: - if self.startX + clipperWidth > frameWidth: - self.startX = frameWidth - clipperWidth - endScrollX = 1.0 - else: - if self.startX < 0: - self.startX = 0 - endScrollX = (self.startX + clipperWidth) / float(frameWidth) - relwidth = '' - - # Position frame relative to clipper. - self._hsframe.place(x = -self.startX, relwidth = relwidth) - return (self.startX / float(frameWidth), endScrollX) - - def _getyview(self): - - # Vertical dimension. - clipperHeight = self._vclipper.winfo_height() - frameHeight = self._vsframe.winfo_reqheight() - if frameHeight <= clipperHeight: - # The scrolled frame is smaller than the clipping window. - - self.startY = 0 - endScrollY = 1.0 - - if self['vertflex'] in ('expand', 'elastic'): - relheight = 1 - else: - relheight = '' - else: - # The scrolled frame is larger than the clipping window. - - if self['vertflex'] in ('shrink', 'elastic'): - self.startY = 0 - endScrollY = 1.0 - relheight = 1 - else: - if self.startY + clipperHeight > frameHeight: - self.startY = frameHeight - clipperHeight - endScrollY = 1.0 - else: - if self.startY < 0: - self.startY = 0 - endScrollY = (self.startY + clipperHeight) / float(frameHeight) - relheight = '' - - # Position frame relative to clipper. - self._vsframe.place(y = -self.startY, relheight = relheight) - return (self.startY / float(frameHeight), endScrollY) - - # According to the relative geometries of the frame and the - # clipper, reposition the frame within the clipper and reset the - # scrollbars. - def _scrollBothNow(self): - self.scrollTimer = None - - # Call update_idletasks to make sure that the containing frame - # has been resized before we attempt to set the scrollbars. - # Otherwise the scrollbars may be mapped/unmapped continuously. - self._scrollRecurse = self._scrollRecurse + 1 - self.update_idletasks() - self._scrollRecurse = self._scrollRecurse - 1 - if self._scrollRecurse != 0: - return - - xview = self._getxview() - yview = self._getyview() - self._horizScrollbar.set(xview[0], xview[1]) - self._vertScrollbar.set(yview[0], yview[1]) - - self._horizScrollbarNeeded = (xview != (0.0, 1.0)) - self._vertScrollbarNeeded = (yview != (0.0, 1.0)) - - # If both horizontal and vertical scrollmodes are dynamic and - # currently only one scrollbar is mapped and both should be - # toggled, then unmap the mapped scrollbar. This prevents a - # continuous mapping and unmapping of the scrollbars. - if (self['hscrollmode'] == self['vscrollmode'] == 'dynamic' and - self._horizScrollbarNeeded != self._horizScrollbarOn and - self._vertScrollbarNeeded != self._vertScrollbarOn and - self._vertScrollbarOn != self._horizScrollbarOn): - if self._horizScrollbarOn: - self._toggleHorizScrollbar() - else: - self._toggleVertScrollbar() - return - - if self['hscrollmode'] == 'dynamic': - if self._horizScrollbarNeeded != self._horizScrollbarOn: - self._toggleHorizScrollbar() - - if self['vscrollmode'] == 'dynamic': - if self._vertScrollbarNeeded != self._vertScrollbarOn: - self._toggleVertScrollbar() - - def _toggleHorizScrollbar(self): - - self._horizScrollbarOn = not self._horizScrollbarOn - - interior = self.origInterior - if self._horizScrollbarOn: - self._horizScrollbar.grid(row = 5, column = 2, sticky = 'news') - interior.grid_rowconfigure(4, minsize = self['scrollmargin']) - else: - self._horizScrollbar.grid_forget() - interior.grid_rowconfigure(4, minsize = 0) - - def _toggleVertScrollbar(self): - - self._vertScrollbarOn = not self._vertScrollbarOn - - interior = self.origInterior - if self._vertScrollbarOn: - self._vertScrollbar.grid(row = 3, column = 4, sticky = 'news') - interior.grid_columnconfigure(3, minsize = self['scrollmargin']) - else: - self._vertScrollbar.grid_forget() - interior.grid_columnconfigure(3, minsize = 0) - - # ====================================================================== - - # Selection methods. - - #def _vsframeselect(self, event): - # print 'vsframe event x: %d y: %d'%(event.x, event.y) - # col, row = self._vsframe.grid_location(event.x, event.y) - # self._select(col, row) - - def _cellframeselect(self, event): - #print 'cellframe event x: %d y: %d'%(event.x, event.y) - x = event.widget.winfo_x() - y = event.widget.winfo_y() - #col, row = self._vsframe.grid_location(x + event.x, y + event.y) - self._select(x + event.x, y + event.y)#(col, row) - - def _cellselect(self, event): - #print 'cell event x: %d y: %d'%(event.x, event.y) - lx = event.widget.winfo_x() - ly = event.widget.winfo_y() - parent = event.widget.pack_info()['in'] - fx = parent.winfo_x() - fy = parent.winfo_y() - #col, row = self._vsframe.grid_location(fx + lx + event.x, fy + ly + event.y) - self._select(fx + lx + event.x, fy + ly + event.y)#(col, row) - - def _select(self, x, y): - col, row = self._vsframe.grid_location(x, y) - #print 'Clicked on col: %d row: %d'%(col,row) - cfg = {} - lineid = self._lineitems[row] - cfg['Cellrowid.%d_foreground'%lineid] = self['selectforeground'] - cfg['Cellrowid.%d_background'%lineid] = self['selectbackground'] - cfg['Cellframerowid.%d_background'%lineid] = self['selectbackground'] - #cfg['Cellframerowid%d_relief'%row] = 'raised' - - if self._cursel != []: - cursel = self._cursel[0] - lineid = self._lineitems[cursel] - if cursel != None and cursel != row: - cfg['Cellrowid.%d_foreground'%lineid] = self['foreground'] - cfg['Cellrowid.%d_background'%lineid] = self['background'] - cfg['Cellframerowid.%d_background'%lineid] = self['background'] - #cfg['Cellframerowid%d_relief'%cursel] = 'flat' - - apply(self.configure, (), cfg) - self._cursel = [row] - - cmd = self['command'] - if callable(cmd): - cmd() - - - - def _cellframedblclick(self, event): - #print 'double click cell frame' - cmd = self['dblclickcommand'] - if callable(cmd): - cmd() - - def _celldblclick(self, event): - #print 'double click cell' - cmd = self['dblclickcommand'] - if callable(cmd): - cmd() - -if __name__ == '__main__': - - rootWin = Tkinter.Tk() - - Pmw.initialise() - - rootWin.title('MultiColumnListbox Demo') - rootWin.configure(width = 500, height = 300) - rootWin.update() - - def dbl(): - print listbox.getcurselection() - - listbox = MultiColumnListbox(rootWin, - #usehullsize = 1, - labellist = ('Column 0', - 'Column 1', - 'Column 2', - 'Column 3', - 'Column 4', - #'Column 5', - #'Column 6', - #'Column 7', - #'Column 8', - #'Column 9', - ), - horizflex = 'expand', - #vertflex = 'elastic', - dblclickcommand = dbl, - ) - - - #print 'start adding item' - for i in range(20): - r = {} - for j in range(5): - r[('Column %d'%j)] = 'Really long item name %d'%i - listbox.addrow(r) - #print 'items added' - - listbox.pack(expand = 1, fill = 'both', padx = 10, pady = 10) - - - exitButton = Tkinter.Button(rootWin, text="Quit", command=rootWin.quit) - exitButton.pack(side = 'left', padx = 10, pady = 10) - - rootWin.mainloop() diff --git a/Pmw/Pmw_1_2/contrib/PmwFileDialog.py b/Pmw/Pmw_1_2/contrib/PmwFileDialog.py deleted file mode 100644 index dc7b4616..00000000 --- a/Pmw/Pmw_1_2/contrib/PmwFileDialog.py +++ /dev/null @@ -1,498 +0,0 @@ -# -__version__ = '$Id: PmwFileDialog.py,v 1.2 2002/08/23 15:03:35 gregm Exp $' -# -# Filename dialogs using Pmw -# -# (C) Rob W.W. Hooft, Nonius BV, 1998 -# -# Modifications: -# -# J. Willem M. Nissink, Cambridge Crystallographic Data Centre, 8/2002 -# Added optional information pane at top of dialog; if option -# 'info' is specified, the text given will be shown (in blue). -# Modified example to show both file and directory-type dialog -# -# No Guarantees. Distribute Freely. -# Please send bug-fixes/patches/features to -# -################################################################################ -import os,fnmatch,time -import Tkinter,Pmw -#Pmw.setversion("0.8.5") - -def _errorpop(master,text): - d=Pmw.MessageDialog(master, - title="Error", - message_text=text, - buttons=("OK",)) - d.component('message').pack(ipadx=15,ipady=15) - d.activate() - d.destroy() - -class PmwFileDialog(Pmw.Dialog): - """File Dialog using Pmw""" - def __init__(self, parent = None, **kw): - # Define the megawidget options. - optiondefs = ( - ('filter', '*', self.newfilter), - ('directory', os.getcwd(), self.newdir), - ('filename', '', self.newfilename), - ('historylen',10, None), - ('command', None, None), - ('info', None, None), - ) - self.defineoptions(kw, optiondefs) - # Initialise base class (after defining options). - Pmw.Dialog.__init__(self, parent) - - self.withdraw() - - # Create the components. - interior = self.interior() - - if self['info'] is not None: - rowoffset=1 - dn = self.infotxt() - dn.grid(row=0,column=0,columnspan=2,padx=3,pady=3) - else: - rowoffset=0 - - dn = self.mkdn() - dn.grid(row=0+rowoffset,column=0,columnspan=2,padx=3,pady=3) - del dn - - # Create the directory list component. - dnb = self.mkdnb() - dnb.grid(row=1+rowoffset,column=0,sticky='news',padx=3,pady=3) - del dnb - - # Create the filename list component. - fnb = self.mkfnb() - fnb.grid(row=1+rowoffset,column=1,sticky='news',padx=3,pady=3) - del fnb - - # Create the filter entry - ft = self.mkft() - ft.grid(row=2+rowoffset,column=0,columnspan=2,padx=3,pady=3) - del ft - - # Create the filename entry - fn = self.mkfn() - fn.grid(row=3+rowoffset,column=0,columnspan=2,padx=3,pady=3) - fn.bind('',self.okbutton) - del fn - - # Buttonbox already exists - bb=self.component('buttonbox') - bb.add('OK',command=self.okbutton) - bb.add('Cancel',command=self.cancelbutton) - del bb - - Pmw.alignlabels([self.component('filename'), - self.component('filter'), - self.component('dirname')]) - - def infotxt(self): - """ Make information block component at the top """ - return self.createcomponent( - 'infobox', - (), None, - Tkinter.Label, (self.interior(),), - width=51, - relief='groove', - foreground='darkblue', - justify='left', - text=self['info'] - ) - - def mkdn(self): - """Make directory name component""" - return self.createcomponent( - 'dirname', - (), None, - Pmw.ComboBox, (self.interior(),), - entryfield_value=self['directory'], - entryfield_entry_width=40, - entryfield_validate=self.dirvalidate, - selectioncommand=self.setdir, - labelpos='w', - label_text='Directory:') - - def mkdnb(self): - """Make directory name box""" - return self.createcomponent( - 'dirnamebox', - (), None, - Pmw.ScrolledListBox, (self.interior(),), - label_text='directories', - labelpos='n', - hscrollmode='none', - dblclickcommand=self.selectdir) - - def mkft(self): - """Make filter""" - return self.createcomponent( - 'filter', - (), None, - Pmw.ComboBox, (self.interior(),), - entryfield_value=self['filter'], - entryfield_entry_width=40, - selectioncommand=self.setfilter, - labelpos='w', - label_text='Filter:') - - def mkfnb(self): - """Make filename list box""" - return self.createcomponent( - 'filenamebox', - (), None, - Pmw.ScrolledListBox, (self.interior(),), - label_text='files', - labelpos='n', - hscrollmode='none', - selectioncommand=self.singleselectfile, - dblclickcommand=self.selectfile) - - def mkfn(self): - """Make file name entry""" - return self.createcomponent( - 'filename', - (), None, - Pmw.ComboBox, (self.interior(),), - entryfield_value=self['filename'], - entryfield_entry_width=40, - entryfield_validate=self.filevalidate, - selectioncommand=self.setfilename, - labelpos='w', - label_text='Filename:') - - def dirvalidate(self,string): - if os.path.isdir(string): - return Pmw.OK - else: - return Pmw.PARTIAL - - def filevalidate(self,string): - if string=='': - return Pmw.PARTIAL - elif os.path.isfile(string): - return Pmw.OK - elif os.path.exists(string): - return Pmw.PARTIAL - else: - return Pmw.OK - - def okbutton(self): - """OK action: user thinks he has input valid data and wants to - proceed. This is also called by in the filename entry""" - fn=self.component('filename').get() - self.setfilename(fn) - if self.validate(fn): - self.canceled=0 - self.deactivate() - - def cancelbutton(self): - """Cancel the operation""" - self.canceled=1 - self.deactivate() - - def tidy(self,w,v): - """Insert text v into the entry and at the top of the list of - the combobox w, remove duplicates""" - if not v: - return - entry=w.component('entry') - entry.delete(0,'end') - entry.insert(0,v) - list=w.component('scrolledlist') - list.insert(0,v) - index=1 - while indexself['historylen']: - list.delete(index) - else: - index=index+1 - w.checkentry() - - def setfilename(self,value): - if not value: - return - value=os.path.join(self['directory'],value) - dir,fil=os.path.split(value) - self.configure(directory=dir,filename=value) - - c=self['command'] - if callable(c): - c() - - def newfilename(self): - """Make sure a newly set filename makes it into the combobox list""" - self.tidy(self.component('filename'),self['filename']) - - def setfilter(self,value): - self.configure(filter=value) - - def newfilter(self): - """Make sure a newly set filter makes it into the combobox list""" - self.tidy(self.component('filter'),self['filter']) - self.fillit() - - def setdir(self,value): - self.configure(directory=value) - - def newdir(self): - """Make sure a newly set dirname makes it into the combobox list""" - self.tidy(self.component('dirname'),self['directory']) - self.fillit() - - def singleselectfile(self): - """Single click in file listbox. Move file to "filename" combobox""" - cs=self.component('filenamebox').curselection() - if cs!=(): - value=self.component('filenamebox').get(cs) - self.setfilename(value) - - def selectfile(self): - """Take the selected file from the filename, normalize it, and OK""" - self.singleselectfile() - value=self.component('filename').get() - self.setfilename(value) - if value: - self.okbutton() - - def selectdir(self): - """Take selected directory from the dirnamebox into the dirname""" - cs=self.component('dirnamebox').curselection() - if cs!=(): - value=self.component('dirnamebox').get(cs) - dir=self['directory'] - if not dir: - dir=os.getcwd() - if value: - if value=='..': - dir=os.path.split(dir)[0] - else: - dir=os.path.join(dir,value) - self.configure(directory=dir) - self.fillit() - - def askfilename(self,directory=None,filter=None): - """The actual client function. Activates the dialog, and - returns only after a valid filename has been entered - (return value is that filename) or when canceled (return - value is None)""" - if directory!=None: - self.configure(directory=directory) - if filter!=None: - self.configure(filter=filter) - self.fillit() - self.canceled=1 # Needed for when user kills dialog window - self.activate() - if self.canceled: - return None - else: - return self.component('filename').get() - - lastdir="" - lastfilter=None - lasttime=0 - def fillit(self): - """Get the directory list and show it in the two listboxes""" - # Do not run unnecesarily - if self.lastdir==self['directory'] and self.lastfilter==self['filter'] and self.lasttime>os.stat(self.lastdir)[8]: - return - self.lastdir=self['directory'] - self.lastfilter=self['filter'] - self.lasttime=time.time() - dir=self['directory'] - if not dir: - dir=os.getcwd() - dirs=['..'] - files=[] - try: - fl=os.listdir(dir) - fl.sort() - except os.error,arg: - if arg[0] in (2,20): - return - raise - for f in fl: - if os.path.isdir(os.path.join(dir,f)): - dirs.append(f) - else: - filter=self['filter'] - if not filter: - filter='*' - if fnmatch.fnmatch(f,filter): - files.append(f) - self.component('filenamebox').setlist(files) - self.component('dirnamebox').setlist(dirs) - - def validate(self,filename): - """Validation function. Should return 1 if the filename is valid, - 0 if invalid. May pop up dialogs to tell user why. Especially - suited to subclasses: i.e. only return 1 if the file does/doesn't - exist""" - return 1 - -class PmwDirDialog(PmwFileDialog): - """Directory Dialog using Pmw""" - def __init__(self, parent = None, **kw): - # Define the megawidget options. - optiondefs = ( - ('directory', os.getcwd(), self.newdir), - ('historylen',10, None), - ('command', None, None), - ('info', None, None), - ) - self.defineoptions(kw, optiondefs) - # Initialise base class (after defining options). - Pmw.Dialog.__init__(self, parent) - - self.withdraw() - - # Create the components. - interior = self.interior() - - if self['info'] is not None: - rowoffset=1 - dn = self.infotxt() - dn.grid(row=0,column=0,columnspan=2,padx=3,pady=3) - else: - rowoffset=0 - - dn = self.mkdn() - dn.grid(row=1+rowoffset,column=0,columnspan=2,padx=3,pady=3) - dn.bind('',self.okbutton) - del dn - - # Create the directory list component. - dnb = self.mkdnb() - dnb.grid(row=0+rowoffset,column=0,columnspan=2,sticky='news',padx=3,pady=3) - del dnb - - # Buttonbox already exists - bb=self.component('buttonbox') - bb.add('OK',command=self.okbutton) - bb.add('Cancel',command=self.cancelbutton) - del bb - - lastdir="" - def fillit(self): - """Get the directory list and show it in the two listboxes""" - # Do not run unnecesarily - if self.lastdir==self['directory']: - return - self.lastdir=self['directory'] - dir=self['directory'] - if not dir: - dir=os.getcwd() - dirs=['..'] - try: - fl=os.listdir(dir) - fl.sort() - except os.error,arg: - if arg[0] in (2,20): - return - raise - for f in fl: - if os.path.isdir(os.path.join(dir,f)): - dirs.append(f) - self.component('dirnamebox').setlist(dirs) - - def okbutton(self): - """OK action: user thinks he has input valid data and wants to - proceed. This is also called by in the dirname entry""" - fn=self.component('dirname').get() - self.configure(directory=fn) - if self.validate(fn): - self.canceled=0 - self.deactivate() - - def askfilename(self,directory=None): - """The actual client function. Activates the dialog, and - returns only after a valid filename has been entered - (return value is that filename) or when canceled (return - value is None)""" - if directory!=None: - self.configure(directory=directory) - self.fillit() - self.activate() - if self.canceled: - return None - else: - return self.component('dirname').get() - - def dirvalidate(self,string): - if os.path.isdir(string): - return Pmw.OK - elif os.path.exists(string): - return Pmw.PARTIAL - else: - return Pmw.OK - - def validate(self,filename): - """Validation function. Should return 1 if the filename is valid, - 0 if invalid. May pop up dialogs to tell user why. Especially - suited to subclasses: i.e. only return 1 if the file does/doesn't - exist""" - if filename=='': - _errorpop(self.interior(),"Empty filename") - return 0 - if os.path.isdir(filename) or not os.path.exists(filename): - return 1 - else: - _errorpop(self.interior(),"This is not a directory") - return 0 - -class PmwExistingFileDialog(PmwFileDialog): - def filevalidate(self,string): - if os.path.isfile(string): - return Pmw.OK - else: - return Pmw.PARTIAL - - def validate(self,filename): - if os.path.isfile(filename): - return 1 - elif os.path.exists(filename): - _errorpop(self.interior(),"This is not a plain file") - return 0 - else: - _errorpop(self.interior(),"Please select an existing file") - return 0 - -class PmwExistingDirDialog(PmwDirDialog): - def dirvalidate(self,string): - if os.path.isdir(string): - return Pmw.OK - else: - return Pmw.PARTIAL - - def validate(self,filename): - if os.path.isdir(filename): - return 1 - elif os.path.exists(filename): - _errorpop(self.interior(),"This is not a directory") - return 0 - else: - _errorpop(self.interior(),"Please select an existing directory") - -if __name__=="__main__": - root=Tkinter.Tk() - root.withdraw() - Pmw.initialise() - - f0=PmwFileDialog(root) - f0.title('File name dialog') - n=f0.askfilename() - print '\nFilename : ',repr(n),'\n' - - f1=PmwDirDialog(root,info='This is a directory dialog') - f1.title('Directory name dialog') - while 1: - n=f1.askfilename() - if n is None: - break - print "Dirname : ",repr(n) diff --git a/Pmw/Pmw_1_2/contrib/PmwFullTimeCounter.py b/Pmw/Pmw_1_2/contrib/PmwFullTimeCounter.py deleted file mode 100644 index 84e605a3..00000000 --- a/Pmw/Pmw_1_2/contrib/PmwFullTimeCounter.py +++ /dev/null @@ -1,492 +0,0 @@ -# Authors: Joe VanAndel, Greg McFarlane and Daniel Michelson - -import string -import sys -import time -import Tkinter -import Pmw - -class FullTimeCounter(Pmw.MegaWidget): - """Up-down counter - - A TimeCounter is a single-line entry widget with Up and Down arrows - which increment and decrement the Time value in the entry. - """ - - def __init__(self, parent = None, **kw): - - # Define the megawidget options. - INITOPT = Pmw.INITOPT - optiondefs = ( - ('autorepeat', 1, INITOPT), - ('buttonaspect', 1.0, INITOPT), - ('initwait', 300, INITOPT), - ('labelmargin', 0, INITOPT), - ('labelpos', None, INITOPT), - ('max', '', self._max), - ('min', '', self._min), - ('padx', 0, INITOPT), - ('pady', 0, INITOPT), - ('repeatrate', 50, INITOPT), - ('value', '', INITOPT), - ) - self.defineoptions(kw, optiondefs) - - # Initialise the base class (after defining the options). - Pmw.MegaWidget.__init__(self, parent) - - self.arrowDirection = {} - self._flag = 'stopped' - self._timerId = None - - self._createComponents() - - value = self['value'] - if value is None or value == '': - now = time.time() - value = time.strftime('%Y:%m:%d:%H:%M',time.gmtime(now)) - self._setTimeFromStr(value) - - # Check keywords and initialise options. - self.initialiseoptions() - - def _createComponents(self): - - # Create the components. - interior = self.interior() - - # If there is no label, put the arrows and the entry directly - # into the interior, otherwise create a frame for them. In - # either case the border around the arrows and the entry will - # be raised (but not around the label). - if self['labelpos'] is None: - frame = interior - else: - frame = self.createcomponent('frame', - (), None, - Tkinter.Frame, (interior,)) - frame.grid(column=2, row=2, sticky='nsew') - interior.grid_columnconfigure(2, weight=1) - interior.grid_rowconfigure(2, weight=1) - - frame.configure(relief = 'raised', borderwidth = 1) - - # Create the down arrow buttons. - - # Create the year down arrow. - self._downYearArrowBtn = self.createcomponent('downyeararrow', - (), 'Arrow', - Tkinter.Canvas, (frame,), - width = 16, height = 16, relief = 'raised', borderwidth = 2) - self.arrowDirection[self._downYearArrowBtn] = 0 - self._downYearArrowBtn.grid(column = 0, row = 2) - - # Create the month down arrow. - self._downMonthArrowBtn = self.createcomponent('downmontharrow', - (), 'Arrow', - Tkinter.Canvas, (frame,), - width = 16, height = 16, relief = 'raised', borderwidth = 2) - self.arrowDirection[self._downMonthArrowBtn] = 0 - self._downMonthArrowBtn.grid(column = 1, row = 2) - - # Create the day down arrow. - self._downDayArrowBtn = self.createcomponent('downdayarrow', - (), 'Arrow', - Tkinter.Canvas, (frame,), - width = 16, height = 16, relief = 'raised', borderwidth = 2) - self.arrowDirection[self._downDayArrowBtn] = 0 - self._downDayArrowBtn.grid(column = 2, row = 2) - - # Create the hour down arrow. - self._downHourArrowBtn = self.createcomponent('downhourarrow', - (), 'Arrow', - Tkinter.Canvas, (frame,), - width = 16, height = 16, relief = 'raised', borderwidth = 2) - self.arrowDirection[self._downHourArrowBtn] = 0 - self._downHourArrowBtn.grid(column = 3, row = 2) - - # Create the minute down arrow. - self._downMinuteArrowBtn = self.createcomponent('downminutearrow', - (), 'Arrow', - Tkinter.Canvas, (frame,), - width = 16, height = 16, relief = 'raised', borderwidth = 2) - self.arrowDirection[self._downMinuteArrowBtn] = 0 - self._downMinuteArrowBtn.grid(column = 4, row = 2) - - # Create the entry fields. - - # Create the year entry field. - self._yearCounterEntry = self.createcomponent('yearentryfield', - (('yearentry', 'yearentryfield_entry'),), None, - Pmw.EntryField, (frame,), validate='integer', entry_width = 4) - self._yearCounterEntry.grid(column = 0, row = 1, sticky = 'news') - - # Create the month entry field. - self._monthCounterEntry = self.createcomponent('monthentryfield', - (('monthentry', 'monthentryfield_entry'),), None, - Pmw.EntryField, (frame,), validate='integer', entry_width = 2) - self._monthCounterEntry.grid(column = 1, row = 1, sticky = 'news') - - # Create the day entry field. - self._dayCounterEntry = self.createcomponent('dayentryfield', - (('dayentry', 'dayentryfield_entry'),), None, - Pmw.EntryField, (frame,), validate='integer', entry_width = 2) - self._dayCounterEntry.grid(column = 2, row = 1, sticky = 'news') - - # Create the hour entry field. - self._hourCounterEntry = self.createcomponent('hourentryfield', - (('hourentry', 'hourentryfield_entry'),), None, - Pmw.EntryField, (frame,), validate='integer', entry_width = 2) - self._hourCounterEntry.grid(column = 3, row = 1, sticky = 'news') - - # Create the minute entry field. - self._minuteCounterEntry = self.createcomponent('minuteentryfield', - (('minuteentry', 'minuteentryfield_entry'),), None, - Pmw.EntryField, (frame,), validate='integer', entry_width = 2) - self._minuteCounterEntry.grid(column = 4, row = 1, sticky = 'news') - - # Create the up arrow buttons. - - # Create the year up arrow. - self._upYearArrowBtn = self.createcomponent('upyeararrow', - (), 'Arrow', - Tkinter.Canvas, (frame,), - width = 16, height = 16, relief = 'raised', borderwidth = 2) - self.arrowDirection[self._upYearArrowBtn] = 1 - self._upYearArrowBtn.grid(column = 0, row = 0) - - # Create the month up arrow. - self._upMonthArrowBtn = self.createcomponent('upmontharrow', - (), 'Arrow', - Tkinter.Canvas, (frame,), - width = 16, height = 16, relief = 'raised', borderwidth = 2) - self.arrowDirection[self._upMonthArrowBtn] = 1 - self._upMonthArrowBtn.grid(column = 1, row = 0) - - # Create the day up arrow. - self._upDayArrowBtn = self.createcomponent('updayarrow', - (), 'Arrow', - Tkinter.Canvas, (frame,), - width = 16, height = 16, relief = 'raised', borderwidth = 2) - self.arrowDirection[self._upDayArrowBtn] = 1 - self._upDayArrowBtn.grid(column = 2, row = 0) - - # Create the hour up arrow. - self._upHourArrowBtn = self.createcomponent('uphourarrow', - (), 'Arrow', - Tkinter.Canvas, (frame,), - width = 16, height = 16, relief = 'raised', borderwidth = 2) - self.arrowDirection[self._upHourArrowBtn] = 1 - self._upHourArrowBtn.grid(column = 3, row = 0) - - # Create the minute up arrow. - self._upMinuteArrowBtn = self.createcomponent('upminutearrow', - (), 'Arrow', - Tkinter.Canvas, (frame,), - width = 16, height = 16, relief = 'raised', borderwidth = 2) - self.arrowDirection[self._upMinuteArrowBtn] = 1 - self._upMinuteArrowBtn.grid(column = 4, row = 0) - - # Make it resize nicely. - padx = self['padx'] - pady = self['pady'] - for col in range(5): # YY, MM, DD, HH, mm - frame.grid_columnconfigure(col, weight = 1, pad = padx) - frame.grid_rowconfigure(0, pad = pady) - frame.grid_rowconfigure(2, pad = pady) - - frame.grid_rowconfigure(1, weight = 1) - - # Create the label. - self.createlabel(interior) - - # Set bindings. - - # Up year - self._upYearArrowBtn.bind('', - lambda event, s=self,button=self._upYearArrowBtn: - s._drawArrow(button, 1)) - self._upYearArrowBtn.bind('<1>', - lambda event, s=self,button=self._upYearArrowBtn: - s._countUp(button)) - self._upYearArrowBtn.bind('', - lambda event, s=self, button=self._upYearArrowBtn: - s._stopUpDown(button)) - - # Up month - self._upMonthArrowBtn.bind('', - lambda event, s=self,button=self._upMonthArrowBtn: - s._drawArrow(button, 1)) - self._upMonthArrowBtn.bind('<1>', - lambda event, s=self,button=self._upMonthArrowBtn: - s._countUp(button)) - self._upMonthArrowBtn.bind('', - lambda event, s=self, button=self._upMonthArrowBtn: - s._stopUpDown(button)) - - # Up day - self._upDayArrowBtn.bind('', - lambda event, s=self,button=self._upDayArrowBtn: - s._drawArrow(button, 1)) - self._upDayArrowBtn.bind('<1>', - lambda event, s=self,button=self._upDayArrowBtn: - s._countUp(button)) - self._upDayArrowBtn.bind('', - lambda event, s=self, button=self._upDayArrowBtn: - s._stopUpDown(button)) - - # Up hour - self._upHourArrowBtn.bind('', - lambda event, s=self,button=self._upHourArrowBtn: - s._drawArrow(button, 1)) - self._upHourArrowBtn.bind('<1>', - lambda event, s=self,button=self._upHourArrowBtn: - s._countUp(button)) - self._upHourArrowBtn.bind('', - lambda event, s=self, button=self._upHourArrowBtn: - s._stopUpDown(button)) - - # Up minute - self._upMinuteArrowBtn.bind('', - lambda event, s=self,button=self._upMinuteArrowBtn: - s._drawArrow(button, 1)) - self._upMinuteArrowBtn.bind('<1>', - lambda event, s=self,button=self._upMinuteArrowBtn: - s._countUp(button)) - self._upMinuteArrowBtn.bind('', - lambda event, s=self, button=self._upMinuteArrowBtn: - s._stopUpDown(button)) - - - # Down year - self._downYearArrowBtn.bind('', - lambda event, s=self,button=self._downYearArrowBtn: - s._drawArrow(button, 0)) - self._downYearArrowBtn.bind('<1>', - lambda event, s=self,button=self._downYearArrowBtn: - s._countDown(button)) - self._downYearArrowBtn.bind('', - lambda event, s=self, button=self._downYearArrowBtn: - s._stopUpDown(button)) - - # Down month - self._downMonthArrowBtn.bind('', - lambda event, s=self,button=self._downMonthArrowBtn: - s._drawArrow(button, 0)) - self._downMonthArrowBtn.bind('<1>', - lambda event, s=self,button=self._downMonthArrowBtn: - s._countDown(button)) - self._downMonthArrowBtn.bind('', - lambda event, s=self, button=self._downMonthArrowBtn: - s._stopUpDown(button)) - - # Down day - self._downDayArrowBtn.bind('', - lambda event, s=self,button=self._downDayArrowBtn: - s._drawArrow(button, 0)) - self._downDayArrowBtn.bind('<1>', - lambda event, s=self,button=self._downDayArrowBtn: - s._countDown(button)) - self._downDayArrowBtn.bind('', - lambda event, s=self, button=self._downDayArrowBtn: - s._stopUpDown(button)) - - # Down hour - self._downHourArrowBtn.bind('', - lambda event, s=self,button=self._downHourArrowBtn: - s._drawArrow(button, 0)) - self._downHourArrowBtn.bind('<1>', - lambda event, s=self,button=self._downHourArrowBtn: - s._countDown(button)) - self._downHourArrowBtn.bind('', - lambda event, s=self, button=self._downHourArrowBtn: - s._stopUpDown(button)) - - # Down minute - self._downMinuteArrowBtn.bind('', - lambda event, s=self,button=self._downMinuteArrowBtn: - s._drawArrow(button, 0)) - self._downMinuteArrowBtn.bind('<1>', - lambda event, s=self,button=self._downMinuteArrowBtn: s._countDown(button)) - self._downMinuteArrowBtn.bind('', - lambda event, s=self, button=self._downMinuteArrowBtn: - s._stopUpDown(button)) - - - self._yearCounterEntry.bind('', self.invoke) - self._monthCounterEntry.bind('', self.invoke) - self._dayCounterEntry.bind('', self.invoke) - self._hourCounterEntry.bind('', self.invoke) - self._minuteCounterEntry.bind('', self.invoke) - - self._yearCounterEntry.bind('', self._resizeArrow) - self._monthCounterEntry.bind('', self._resizeArrow) - self._dayCounterEntry.bind('', self._resizeArrow) - self._hourCounterEntry.bind('', self._resizeArrow) - self._minuteCounterEntry.bind('', self._resizeArrow) - - def _drawArrow(self, arrow, direction): - arrow.delete('arrow') - - fg = self._yearCounterEntry.cget('entry_foreground') - - bw = (string.atoi(arrow['borderwidth']) + - string.atoi(arrow['highlightthickness'])) / 2 - h = string.atoi(arrow['height']) + 2 * bw - w = string.atoi(arrow['width']) + 2 * bw - - if direction == 0: - # down arrow - arrow.create_polygon( - 0.25 * w + bw, 0.25 * h + bw, - 0.50 * w + bw, 0.75 * h + bw, - 0.75 * w + bw, 0.25 * h + bw, - fill=fg, tag='arrow') - else: - arrow.create_polygon( - 0.25 * w + bw, 0.75 * h + bw, - 0.50 * w + bw, 0.25 * h + bw, - 0.75 * w + bw, 0.75 * h + bw, - fill=fg, tag='arrow') - - def _resizeArrow(self, event = None): - for btn in (self._upYearArrowBtn, self._upMonthArrowBtn, - self._upDayArrowBtn, self._upHourArrowBtn, - self._upMinuteArrowBtn, self._downYearArrowBtn, - self._downMonthArrowBtn, self._downDayArrowBtn, - self._downHourArrowBtn, self._downMinuteArrowBtn): - bw = (string.atoi(btn['borderwidth']) + \ - string.atoi(btn['highlightthickness'])) - newHeight = self._yearCounterEntry.winfo_reqheight() - 2 * bw - newWidth = newHeight * self['buttonaspect'] - btn.configure(width=newWidth, height=newHeight) - self._drawArrow(btn, self.arrowDirection[btn]) - - def _min(self): - self._minVal = None - - def _max(self): - self._maxVal = None - - def _setTimeFromStr(self, str): - list = string.split(str, ':') - if len(list) != 5: - raise ValueError, 'invalid value: ' + str - - self._year = string.atoi(list[0]) - self._month = string.atoi(list[1]) - self._day = string.atoi(list[2]) - self._hour = string.atoi(list[3]) - self._minute = string.atoi(list[4]) - - self._setHMS() - - def getstring(self): - return '%04d:%02d:%02d:%02d:%02d' % (self._year, self._month, - self._day, self._hour, - self._minute) - - def getint(self): - pass - - def _countUp(self, button): - self._relief = self._upYearArrowBtn.cget('relief') - button.configure(relief='sunken') - if button == self._upYearArrowBtn: datetype = "year" - elif button == self._upMonthArrowBtn: datetype = "month" - elif button == self._upDayArrowBtn: datetype = "day" - elif button == self._upHourArrowBtn: datetype = "hour" - elif button == self._upMinuteArrowBtn: datetype = "minute" - self._count(1, datetype, 'start') - - def _countDown(self, button): - self._relief = self._downYearArrowBtn.cget('relief') - button.configure(relief='sunken') - if button == self._downYearArrowBtn: datetype = "year" - elif button == self._downMonthArrowBtn: datetype = "month" - elif button == self._downDayArrowBtn: datetype = "day" - elif button == self._downHourArrowBtn: datetype = "hour" - elif button == self._downMinuteArrowBtn: datetype = "minute" - self._count(-1, datetype, 'start') - - def _count(self, factor, datetype, newFlag=None): - if newFlag != 'force': - if newFlag is not None: - self._flag = newFlag - - if self._flag == 'stopped': - return - - if datetype == "year": self._year = self._year + factor - elif datetype == "month": self._month = self._month + factor - elif datetype == "day": self._day = self._day + factor - elif datetype == "hour": self._hour = self._hour + factor - elif datetype == "minute": self._minute = self._minute + factor - secs = time.mktime((self._year, self._month, self._day, self._hour, - self._minute, 0, 0, 0, -1)) - tt = time.localtime(secs) # NOT gmtime! - - self._year = tt[0] - self._month = tt[1] - self._day = tt[2] - self._hour = tt[3] - self._minute = tt[4] - self._setHMS() - - if newFlag != 'force': - if self['autorepeat']: - if self._flag == 'start': - delay = self['initwait'] - self._flag = 'running' - else: - delay = self['repeatrate'] - self._timerId = self.after( - delay, lambda self=self, factor=factor, datetype=datetype: - self._count(factor, datetype, 'running')) - - def _setHMS(self): - self._yearCounterEntry.setentry('%04d' % self._year) - self._monthCounterEntry.setentry('%02d' % self._month) - self._dayCounterEntry.setentry('%02d' % self._day) - self._hourCounterEntry.setentry('%02d' % self._hour) - self._minuteCounterEntry.setentry('%02d' % self._minute) - - def _stopUpDown(self, button): - if self._timerId is not None: - self.after_cancel(self._timerId) - self._timerId = None - button.configure(relief=self._relief) - self._flag = 'stopped' - - def invoke(self, event = None): - cmd = self['command'] - if callable(cmd): - cmd() - - def destroy(self): - if self._timerId is not None: - self.after_cancel(self._timerId) - self._timerId = None - Pmw.MegaWidget.destroy(self) - -if __name__=="__main__": - - def showString(): - stringVal = _time.getstring() - print stringVal - - root = Tkinter.Tk() - Pmw.initialise(root) - root.title('FullTimeCounter') - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - - _time = FullTimeCounter(root, - labelpos = 'n', - label_text = 'YYYY:MM:DD:HH:mm') - _time.pack(fill = 'both', expand = 1, padx=10, pady=5) - - button = Tkinter.Button(root, text = 'Show', command = showString) - button.pack() - root.mainloop() diff --git a/Pmw/Pmw_1_2/contrib/PmwVerticalGauge.py b/Pmw/Pmw_1_2/contrib/PmwVerticalGauge.py deleted file mode 100644 index b413f937..00000000 --- a/Pmw/Pmw_1_2/contrib/PmwVerticalGauge.py +++ /dev/null @@ -1,253 +0,0 @@ -""" -I needed a simple gauge, so I've made on with Pmw. -It might be useful for others to use as a base to develop more comples -gauges with. - -Is it worth cleaning up and submitting? - -cheers and thanks - -chris - -Dr. Chris Wright -Intensive Care Unit -Monash Medical Centre -Clayton. VIC Australia -""" - -import sys -import Tkinter -import Pmw -import time - - -if sys.platform == 'win32': - # MS-Windows specific fonts - label_font = "-family Ariel -size 12" - value_font = "-family Ariel -size 12" - small_font = "-family {MS Sans Serif} -size 9 -weight bold" - header_font = "-family {MS Sans Serif} -weight bold" -else: - # X-Windows specific fonts - label_font = "-*-helvetica-*-r-*-*-*-160-*-*-*-*-*-*" - value_font = "-*-courier-*-r-*-*-*-160-*-*-*-*-*-*" - small_font = "-*-helvetica-*-r-*-*-*-130-*-*-*-*-*-*" - header_font = "-*-helvetica-bold-r-*-*-*-150-*-*-*-*-*-*" - -class VerticalGauge(Pmw.MegaWidget): - """Vertical gauge with actual and desired settings""" - - def __init__(self, parent = None, **kw): - optiondefs = ( - ('min', 0, None), - ('max', 100, None), - ('majortickinterval', 10, None), - ('minortickinterval', 5, None), - ('units', '', None), - ('bg', 'grey', self._backgroundSet), - ('actualvalue', 50, self._actualSet), - ('desiredvalue', 50, self._desiredSet), - ('actualcolour', 'yellow1', None), - ('desiredcolour', 'turquoise1', None), - ('label', 'Label', None), - ) - self.defineoptions(kw, optiondefs) - Pmw.MegaWidget.__init__(self, parent) - - interior = self.interior() - interior.grid_rowconfigure(1, weight = 1) - for r in range(3): - interior.grid_columnconfigure(r, weight = 1) - - self.actuallabel = self.createcomponent('actualLabel', - (), None, - Tkinter.Label, (interior,), - text = '', - width = 3, - relief = 'sunken', - bd = 1, - fg = self['actualcolour'], - font = value_font) - self.actuallabel.grid(sticky = "nswe", row = 0, column = 0) - - self.label = self.createcomponent('label', - (), None, - Tkinter.Label, (interior,), - text = self['label'], - relief = 'raised', - font = label_font, - fg = 'navy', - bd = 2) - self.label.grid(sticky = "nsew", row = 0, column = 1) - - self.desiredlabel = self.createcomponent('desiredLabel', - (), None, - Tkinter.Label, (interior,), - text = '', - width = 3, - relief = 'sunken', - bd = 1, - fg = self['desiredcolour'], - font = value_font) - self.desiredlabel.grid(sticky = "nswe", row = 0, column = 2) - - self.canvas = self.createcomponent('canvas', - (), None, - Tkinter.Canvas, (interior,), - width = 100, - height = 300, - bg = 'grey') - - self.canvas.grid(sticky = "nsew", columnspan = 3, pady = 1) - self.canvas.bind("", self._createGaugeAxes) - - self._createGaugeAxes() - - self.initialiseoptions() - - def _createGaugeAxes(self, event = None): - min = self['min'] - max = self['max'] - units = self['units'] - majortickinterval = self['majortickinterval'] - - gauge_range = max - min - - c = self.canvas - c.delete("all") - if event: - h, w = event.height, event.width - else: - h = int(c.configure("height")[4]) - w = int(c.configure("width")[4]) - - self.lower = h - 15 - self.upper = 15 - self.middle = w / 2 - c.create_line(self.middle, self.lower, self.middle, self.upper) - - majortickcount = int((max - min) / majortickinterval) - self.axislength = self.lower - self.upper - self.majortickdistance = float(self.axislength) / majortickcount - self.majortickwidth = w / 5 - labeloffset = (w / 4) + 10 - - for i in range(majortickcount + 1): - v = min + i * majortickinterval - d = self.lower - i * self.majortickdistance - c.create_line(self.middle, d, self.middle + self.majortickwidth, d) - c.create_text(self.middle + labeloffset, d, font = small_font, text = str(v)) - - self._desiredSet(event) - self._actualSet(event) - - def _backgroundSet(self): - self.canvas.configure(bg = self['bg']) - - def _desiredSet(self, event = None): - c = self.canvas - desired = self['desiredvalue'] - desiredcolour = self['desiredcolour'] - - min = self['min'] - max = self['max'] - - if desired > max: desired = max - if desired < min: desired = min - gauge_range = max - min - - c = self.canvas - if event: - h, w = event.height, event.width - else: - h = int(c.configure("height")[4]) - w = int(c.configure("width")[4]) - - - desired_y = self.lower - (float(desired - min) / gauge_range) * self.axislength - - try: - c.delete('desiredBar') - except: - pass - - c.create_line(self.middle - self.majortickwidth, desired_y, - self.middle + self.majortickwidth, desired_y, - fill = desiredcolour, stipple = 'gray50', - width = 10, tag = 'desiredBar') - self.desiredlabel.configure(text = desired) - - def setActual(self, value): - self.configure(actualvalue = value) - - def getActual(self): - return self.cget('actualvalue') - - def _actualSet(self, event = None): - c = self.canvas - actual = self['actualvalue'] - actualcolour = self['actualcolour'] - - min = self['min'] - max = self['max'] - - if actual > max: actual = max - if actual < min: actual = min - gauge_range = max - min - - c = self.canvas - if event: - h, w = event.height, event.width - else: - h = int(c.configure("height")[4]) - w = int(c.configure("width")[4]) - - actual_y = self.lower - (float(actual - min) / gauge_range) * self.axislength - - try: - c.delete('actualPointer') - except: - pass - - triangle = ((self.middle, actual_y), - (self.middle - 1.4 * self.majortickwidth, actual_y - self.majortickwidth / 2), - (self.middle - 1.4 * self.majortickwidth, actual_y + self.majortickwidth / 2)) - - c.create_polygon(triangle, fill = actualcolour, tag = 'actualPointer') - self.actuallabel.configure(text = actual) - - -Pmw.forwardmethods(VerticalGauge, Tkinter.Canvas, 'canvas') - -if __name__ == '__main__': - - - # Initialise Tkinter and Pmw. - root = Pmw.initialise() - root.title('Pmw VerticalGauge demonstration') - - - def increase(): - av = g1.getActual() - g1.setActual(av + 1) - - def decrease(): - av = g1.getActual() - g1.setActual(av - 1) - - g1 = VerticalGauge(min = 0, - max = 30, - actualvalue = 15, - desiredvalue = 22, - majortickinterval = 2, - label = "Pms") - g1.grid(sticky = "nsew") - root.grid_rowconfigure(0, weight = 1) - root.grid_columnconfigure(0, weight = 1) - b1 = Tkinter.Button(text = "Increase", command = increase) - b1.grid() - b2 = Tkinter.Button(text = "Decrease", command = decrease) - b2.grid() - - # Let's go. - root.mainloop() diff --git a/Pmw/Pmw_1_2/contrib/README b/Pmw/Pmw_1_2/contrib/README deleted file mode 100644 index 2662f77e..00000000 --- a/Pmw/Pmw_1_2/contrib/README +++ /dev/null @@ -1,10 +0,0 @@ -This directory contains contributed Pmw megawidgets. - -DirBrowser.py directory selection dialog -MCListbox.py multi-column selectable listbox -PmwFileDialog.py file selection dialog -PmwFullTimeCounter.py time counter which includes year, month and day -PmwVerticalGauge.py a simple gauge indicating a value and a threshold -TreeBrowser.py generic hierarchical tree browser - -Each file can be executed and will display a demo of its megawidget. diff --git a/Pmw/Pmw_1_2/contrib/TreeBrowser.py b/Pmw/Pmw_1_2/contrib/TreeBrowser.py deleted file mode 100644 index 6d9fe89a..00000000 --- a/Pmw/Pmw_1_2/contrib/TreeBrowser.py +++ /dev/null @@ -1,732 +0,0 @@ -# -# FILE: TreeBrowser.py -# -# DESCRIPTION: -# This file provides a generic hierarchical tree browser widget. -# -# AUTHOR: Steve Kinneberg , -# MontaVista Software, Inc. -# -# Copyright 2001 MontaVista Software Inc. -# -# This program is free software; you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by the -# Free Software Foundation; either version 2 of the License, or (at your -# option) any later version. -# -# THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED -# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN -# NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, -# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT -# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# -# You should have received a copy of the GNU General Public License along -# with this program; if not, write to the Free Software Foundation, Inc., -# 675 Mass Ave, Cambridge, MA 02139, USA. -# - - -import types -import Tkinter -import Pmw - - -class _Branching: - def __init__(self): - # List of branch names - self._nodeNames = [] - - # Map from branch name to branch info - # branch Either _LeafNode or _BranchNode widget of the branch - # nodetype Either 'TreeNode' or 'LeafNode' - self._nodeAttrs = {} - - def addbranch(self, branchName = None, **kw): - kw['indent'] = self['indent'] - return apply(self._insertnode, - ('tree', branchName, len(self._nodeNames), - self._treeRoot), - kw) - - def addleaf(self, leafName = None, **kw): - return apply(self._insertnode, - ('leaf', leafName, len(self._nodeNames), - self._treeRoot), - kw) - - def insertbranch(self, branchName = None, before = 0, **kw): - kw['indent'] = self['indent'] - return apply(self._insertnode, - ('tree', branchName, before, self._treeRoot), - kw) - - def insertleaf(self, leafName = None, before = 0, **kw): - return apply(self._insertnode, - ('leaf', leafName, before, self._treeRoot), - kw) - - def _insertnode(self, type, nodeName, before, treeRoot, **kw): - if 'selectbackground' not in kw.keys(): - kw['selectbackground'] = self['selectbackground'] - - if 'selectforeground' not in kw.keys(): - kw['selectforeground'] = self['selectforeground'] - - if 'background' not in kw.keys(): - kw['background'] = self['background'] - - if 'foreground' not in kw.keys(): - kw['foreground'] = self['foreground'] - - if nodeName == None: - nodeName = self._nodeName + ".%d" % (len(self._nodeNames) + 1) - - if self._nodeAttrs.has_key(nodeName): - msg = 'Node "%s" already exists.' % nodeName - raise ValueError, msg - - # Do this early to catch bad spec before creating any items. - beforeIndex = self.index(before, 1) - attributes = {} - - last = (beforeIndex == len(self._nodeNames)) - if last and len(self._nodeNames) > 0: - # set the previous node to not last - self._nodeAttrs[self._nodeNames[-1]]['branch']._setlast(0) - - if(type == 'tree'): - node = apply(self.createcomponent, ('branch%d'%len(self._nodeNames), - (), None, - _BranchNode, - self._branchFrame, - nodeName, - treeRoot, - self, - last, - ), kw) - attributes['nodetype'] = 'TreeNode' - else: - node = apply(self.createcomponent, ('leaf%d'%len(self._nodeNames), - (), None, - _LeafNode, - self._branchFrame, - nodeName, - treeRoot, - self, - last, - ), kw) - attributes['nodetype'] = 'LeafNode' - - if len(self._nodeNames) == beforeIndex: - node.pack(anchor='w') - else: - bname = self._nodeNames[beforeIndex] - battrs = self._nodeAttrs[bname] - node.pack(anchor='w', before=battrs['branch']) - - attributes['branch'] = node - - self._nodeAttrs[nodeName] = attributes - self._nodeNames.insert(beforeIndex, nodeName) - self._sizechange() - return node - - def delete(self, *nodes): - curSel = self._treeRoot.curselection()[0] - for node in nodes: - index = self.index(node) - name = self._nodeNames.pop(index) - dnode = self._nodeAttrs[name]['branch'] - del self._nodeAttrs[name] - if dnode == curSel: - self._treeRoot._unhightlightnode(dnode) - dnode.destroy() - self._sizechange() - - def destroy(self): - for node in len(self._nodeNames): - self.delete(node) - Pmw.MegaWidget.destroy(self) - - def index(self, index, forInsert = 0): - if isinstance(index, _LeafNode): - index = index._nodeName - listLength = len(self._nodeNames) - if type(index) == types.IntType: - if forInsert and index <= listLength: - return index - elif not forInsert and index < listLength: - return index - else: - raise ValueError, 'index "%s" is out of range' % index - elif type(index) == types.StringType: - if index in self._nodeNames: - return self._nodeNames.index(index) - raise ValueError, 'bad branch or leaf name: %s' % index - elif index is Pmw.END: - if forInsert: - return listLength - elif listLength > 0: - return listLength - 1 - else: - raise ValueError, 'TreeNode has no branches' - #elif index is Pmw.SELECT: - # if listLength == 0: - # raise ValueError, 'TreeNode has no branches' - # return self._pageNames.index(self.getcurselection()) - else: - validValues = 'a name, a number, Pmw.END, Pmw.SELECT, or a reference to a TreeBrowser Leaf or Branch' - raise ValueError, \ - 'bad index "%s": must be %s' % (index, validValues) - - def getnodenames(self): - return self._nodeNames - - def getnode(self, node): - nodeName = self._nodeNames[self.index(node)] - return self._nodeAttrs[nodeName]['branch'] - - -class _LeafNode(Pmw.MegaWidget): - - def __init__(self, parent, nodeName, treeRoot, parentnode, last = 1, **kw): - colors = Pmw.Color.getdefaultpalette(parent) - - self._nodeName = nodeName - self._treeRoot = treeRoot - self._parentNode = parentnode - - self._last = last - # Define the megawidget options. - INITOPT = Pmw.INITOPT - optiondefs = ( - ('selectbackground', colors['selectBackground'], INITOPT), - ('selectforeground', colors['selectForeground'], INITOPT), - ('background', colors['background'], INITOPT), - ('foreground', colors['foreground'], INITOPT), - ('selectcommand', None, None), - ('deselectcommand', None, None), - ('labelpos', 'e', INITOPT), - ('labelmargin', 0, INITOPT), - ('label', None, None), - ) - self.defineoptions(kw, optiondefs) - - # Initialise the base class (after defining the options). - Pmw.MegaWidget.__init__(self, parent) - - # Create the components - interior = self._hull - - - labelpos = self['labelpos'] - - if self['label'] == None: - self._labelWidget = self.createcomponent('labelwidget', - (), None, - Pmw.LabeledWidget, - (interior,), - #background = self['background'], - #foreground = self['foreground'], - ) - else: - self._labelWidget = self.createcomponent('labelwidget', - (), None, - Pmw.LabeledWidget, - (interior,), - label_background = self['background'], - label_foreground = self['foreground'], - labelpos = labelpos, - labelmargin = self['labelmargin'], - label_text = self['label'], - ) - self._labelWidget.component('label').bind('', - self._selectevent) - - self._labelWidget.grid(column = 1, row = 0, sticky = 'w') - - self._labelWidget.update() - - self._labelheight = self._labelWidget.winfo_height() - - self._lineCanvas = self.createcomponent('linecanvas', - (), None, - Tkinter.Canvas, - (interior,), - width = self._labelheight, - height = self._labelheight, - ) - self._lineCanvas.grid( column = 0, row = 0, sticky = 'news') - self._lineCanvas.update() - - cw = int(self._lineCanvas['width']) - ch = int(self._lineCanvas['height']) - - self._lineCanvas.create_line(cw/2, ch/2, cw, ch/2, tag='hline') - if last: - self._lineCanvas.create_line(cw/2, 0, cw/2, ch/2, tag='vline') - else: - self._lineCanvas.create_line(cw/2, 0, cw/2, ch, tag='vline') - - # Check keywords and initialise options. - self.initialiseoptions() - - - def interior(self): - return self._labelWidget.interior() - - def select(self): - self._highlight() - - def getname(self): - return self._nodeName - - def getlabel(self): - return self['label'] - - def _selectevent(self, event): - self._highlight() - - def _highlight(self): - self._treeRoot._highlightnode(self) - #self._subHull.configure(background = self._selectbg, relief = 'raised') - if self['label'] != None: - self._labelWidget.configure(label_background = self['selectbackground']) - self._labelWidget.configure(label_foreground = self['selectforeground']) - #self._viewButton.configure(background = self._selectbg) - cmd = self['selectcommand'] - if callable(cmd): - cmd(self) - - def _unhighlight(self): - #self._subHull.configure(background = self._bg, relief = 'flat') - if self['label'] != None: - self._labelWidget.configure(label_background = self['background']) - self._labelWidget.configure(label_foreground = self['foreground']) - #self._viewButton.configure(background = self._bg) - cmd = self['deselectcommand'] - if callable(cmd): - cmd(self) - - def _setlast(self, last): - self._last = last - - cw = int(self._lineCanvas['width']) - ch = int(self._lineCanvas['height']) - - if last: - self._lineCanvas.create_line(cw/2, 0, cw/2, ch/2, tag='vline') - else: - self._lineCanvas.create_line(cw/2, 0, cw/2, ch, tag='vline') - - -class _BranchNode(_LeafNode, _Branching): #Pmw.MegaWidget): - - def __init__(self, parent, nodeName, treeRoot, parentnode, last = 1, **kw): - # Define the megawidget options. - INITOPT = Pmw.INITOPT - optiondefs = ( - ('view', 'collapsed', None), - ('expandcommand', None, None), - ('collapsecommand', None, None), - ('indent', 0, INITOPT) - ) - self.defineoptions(kw, optiondefs) - - # Initialise the base class (after defining the options). - apply(_LeafNode.__init__, - (self, parent, nodeName, treeRoot, parentnode, last), - kw) - _Branching.__init__(self) - - # Create the components - interior = self._hull - - # Create the expand/collapse button - self._viewButton = self.createcomponent('viewbutton', (), None, - Tkinter.Canvas, - (interior,), - background = self['background'], - width = self._labelheight - 4, - height = self._labelheight - 4, - borderwidth = 2, - relief = 'raised') - - self._viewButton.grid(column = 0, row = 0, sticky='se') - self._viewButton.bind('', self._showbuttonpress) - self._viewButton.bind('', self._toggleview) - - # The label widget is already created by the base class, however - # we do need to make some slight modifications. - if self['label'] != None: - self._labelWidget.component('label').bind('', - self._toggleview) - self._labelWidget.grid(column=1, row=0, columnspan = 3, sticky='sw') - - # A line canvas is already created for us, we just need to make - # some slight modifications - self._lineCanvas.delete('hline') - self._lineCanvas.grid_forget() - - - # Set the minsize of column 1 to control additional branch frame indentation - self.grid_columnconfigure(1, minsize = self['indent']) - - # Create the branch frame that will contain all the branch/leaf nodes - self._branchFrame = self.createcomponent('frame', (), None, - Tkinter.Frame, (interior,), - #borderwidth=2, - #relief='ridge', - ) - self.grid_columnconfigure(2,minsize=0, weight=1) - #self.grid_rowconfigure(0,minsize=0) - - if(self['view'] == 'expanded'): - Pmw.drawarrow(self._viewButton, - self['foreground'], - 'down', 'arrow') - self._branchFrame.grid(column = 2, row = 1, sticky='nw') - if not self._last: - self._branchFrame.update() - bh = self._branchFrame.winfo_height() - self._lineCanvas.configure(height = bh) - self._lineCanvas.grid(column = 0, row = 1, sticky='news') - cw = int(self._lineCanvas['width']) - ch = int(self._lineCanvas['height']) - #self._lineCanvas.create_line(cw/2, 1, cw/2, ch, tag = 'vline') - self._lineCanvas.coords('vline', cw/2, 1, cw/2, ch) - else: - Pmw.drawarrow(self._viewButton, - self['foreground'], - 'right', 'arrow') - self._viewButton.configure(relief = 'raised') - - - # Check keywords and initialise options. - self.initialiseoptions() - - - - def _showbuttonpress(self, event): - self._viewButton.configure(relief = 'sunken') - - def _toggleview(self, event): - self._viewButton.configure(relief = 'sunken') - self.select() - if(self['view'] == 'expanded'): - self.collapsetree() - else: - self.expandtree() - self._viewButton.configure(relief = 'raised') - - def expandtree(self): - if(self['view'] == 'collapsed'): - cmd = self['expandcommand'] - if cmd is not None: - cmd(self) - self['view'] = 'expanded' - Pmw.drawarrow(self._viewButton, - self['foreground'], - 'down', 'arrow') - self._branchFrame.grid(column = 2, row = 1, sticky='nw') - - if not self._last: - self._branchFrame.update() - bh = self._branchFrame.winfo_height() - self._lineCanvas.configure(height = bh) - self._lineCanvas.grid(column = 0, row = 1, sticky='news') - cw = int(self._lineCanvas['width']) - ch = int(self._lineCanvas['height']) - #self._lineCanvas.create_line( cw/2, 1, cw/2, ch, tag = 'vline') - self._lineCanvas.coords('vline', cw/2, 1, cw/2, ch) - self._parentNode._sizechange() - - def collapsetree(self): - if(self['view'] == 'expanded'): - cmd = self['collapsecommand'] - if cmd is not None: - cmd(self) - self['view'] = 'collapsed' - Pmw.drawarrow(self._viewButton, - self['foreground'], - 'right', 'arrow') - self._branchFrame.grid_forget() - if not self._last: - #self._lineCanvas.delete('vline') - self._lineCanvas.grid_forget() - self._parentNode._sizechange() - - def _setlast(self, last): - self._last = last - if self['view'] == 'expanded': - self._branchFrame.update() - bh = self._branchFrame.winfo_height() - self._lineCanvas.configure(height = bh) - cw = int(self._lineCanvas['width']) - ch = int(self._lineCanvas['height']) - self._lineCanvas.delete('vline') - if not last: - self._lineCanvas.create_line(cw/2, 1, cw/2, ch, tag='vline') - - - def _sizechange(self): - if not self._last and self['view'] == 'expanded': - self._branchFrame.update() - bh = self._branchFrame.winfo_height() - self._lineCanvas.configure(height = bh) - if self._lineCanvas.coords('vline')[3] < bh: - cw = int(self._lineCanvas['width']) - ch = int(self._lineCanvas['height']) - #self._lineCanvas.delete('vline') - #self._lineCanvas.create_line(cw/2, 1, cw/2, ch, tag='vline') - self._lineCanvas.coords('vline', cw/2, 1, cw/2, ch) - self._parentNode._sizechange() - -class TreeBrowser(Pmw.MegaWidget, _Branching): - - def __init__(self, parent = None, nodeName = '0', **kw): - colors = Pmw.Color.getdefaultpalette(parent) - - # Define the megawidget options. - INITOPT = Pmw.INITOPT - optiondefs = ( - ('indent', 0, INITOPT), - ('selectbackground', colors['selectBackground'], INITOPT), - ('selectforeground', colors['selectForeground'], INITOPT), - ('background', colors['background'], INITOPT), - ('foreground', colors['foreground'], INITOPT), - #('selectrelief', 'raised', INITOPT), - ) - - self.defineoptions(kw, optiondefs) - - # Initialise the base class (after defining the options). - Pmw.MegaWidget.__init__(self, parent) - _Branching.__init__(self) - - - # Create the components - interior = self._hull - - browserFrame = self.createcomponent('frame', (), None, - Pmw.ScrolledFrame, - (interior,), - ) - - browserFrame.pack(expand = 1, fill='both') - - self._branchFrame = browserFrame.interior() - - self._highlightedNode = None - self._treeRoot = self - self._nodeName = nodeName - # Check keywords and initialise options. - self.initialiseoptions() - - def _highlightnode(self, newNode): - if self._highlightedNode != newNode: - if self._highlightedNode != None: - self._highlightedNode._unhighlight() - self._highlightedNode = newNode - - def _unhighlightnode(self): - if self._highlightedNode != None: - self._highlightedNode._unhighlight() - self._highlightedNode = None - - def curselection(self): - retVal = None - if self._highlightedNode != None: - retVal = (self._highlightedNode, - self._highlightedNode._nodeName, - self._highlightedNode['label']) - return retVal - - def getname(self): - return self._nodeName - - # The top-level TreeBrowser widget only shows nodes in an expanded view - # but still provides collapsetree() and expandtree() methods so that users - # don't have to special case the top-level node - - def collapsetree(self): - return - - def expandtree(self): - return - - def _sizechange(self): - return - -if __name__ == '__main__': - - rootWin = Tkinter.Tk() - - Pmw.initialise() - - rootWin.title('TreeBrowser Demo') - - # Create the hierarchical tree browser widget - treeBrowser = TreeBrowser(rootWin, - #selectbackground = "darkgreen", - #selectforeground = 'lightgreen', - #background = 'green', - #indent = 10, - ) - - - def printselected(node): - selection = treeBrowser.curselection() - if selection != None: - print "Selected node name:", selection[1], " label:", selection[2] - - - def printdeselected(node): - selection = treeBrowser.curselection() - if selection != None: - print "Deselected node name:", selection[1], " label:", selection[2] - - def printexpanded(node): - print "Expanded node name:", node.getname(), " label:", node.getlabel() - - def printcollapsed(node): - print "Collapsed node name:", node.getname(), " label:", node.getlabel() - - - - for i in range(3): - # Add a tree node to the top level - treeNodeLevel1 = treeBrowser.addbranch(label = 'TreeNode %d'%i, - selectcommand = printselected, - deselectcommand = printdeselected, - expandcommand = printexpanded, - collapsecommand = printcollapsed, - ) - for j in range(3): - # Add a tree node to the second level - treeNodeLevel2 = treeNodeLevel1.addbranch(label = 'TreeNode %d.%d'%(i,j), - #selectforeground = 'yellow', - selectcommand = printselected, - deselectcommand = printdeselected, - expandcommand = printexpanded, - collapsecommand = printcollapsed, - ) - if i == 0 and j == 1: - dynamicTreeRootNode = treeNodeLevel1 - dynamicTreePosNode = treeNodeLevel2 - - for item in range((i+1)*(j+1)): - # Add a leaf node to the third level - leaf = treeNodeLevel2.addleaf(label = "Item %c"%(item+65), - #selectbackground = 'blue', - selectcommand = printselected, - deselectcommand = printdeselected) - for item in range(i+1): - # Add a leaf node to the top level - leaf = treeNodeLevel1.addleaf(label = "Item %c"%(item+65), - selectcommand = printselected, - deselectcommand = printdeselected) - - - treeNodeLevel1 = treeBrowser.addbranch(label = 'Check Button Label', - selectcommand = printselected, - deselectcommand = printdeselected, - expandcommand = printexpanded, - collapsecommand = printcollapsed, - ) - checkButton = Tkinter.Checkbutton(treeNodeLevel1.interior(), - text = 'Da Check Button', - relief = 'ridge', - command = treeNodeLevel1.select) - checkButton.pack() - - treeNodeLevel1.addleaf(label = 'Labeled Leaf', - selectcommand = printselected, - deselectcommand = printdeselected) - leaf = treeNodeLevel1.addleaf(label = 'Labeled Leaf w/ Checkbutton', - selectcommand = printselected, - deselectcommand = printdeselected) - checkButton = Tkinter.Checkbutton(leaf.interior(), - text = 'Da Check Button', - relief = 'ridge', - command = leaf.select) - checkButton.pack() - - - treeNodeLevel1 = treeBrowser.addbranch(selectcommand = printselected, - deselectcommand = printdeselected, - expandcommand = printexpanded, - collapsecommand = printcollapsed, - ) - checkButton = Tkinter.Checkbutton(treeNodeLevel1.interior(), - text = 'Check Button with no label', - relief = 'ridge', - command = treeNodeLevel1.select) - checkButton.pack() - - treeNodeLevel1 = treeBrowser.addbranch(label = 'Label', - selectcommand = printselected, - deselectcommand = printdeselected, - expandcommand = printexpanded, - collapsecommand = printcollapsed, - ) - - # setup dynamic tree node insertion and removal - class dynTree: - def __init__(self): - self.dyn = Tkinter.IntVar() - self.dtree = None - - self.dLeaf = treeBrowser.addleaf(selectcommand = self.dynSelected, - deselectcommand = self.dynDeselected) - - self.dCheckButton = Tkinter.Checkbutton(self.dLeaf.interior(), - text = 'Enable Dynamic Tree', - variable = self.dyn, - command = self.ChkBtnHandler) - self.dCheckButton.pack() - - - def dynSelected(self, node): - self.dCheckButton.configure(background = self.dLeaf.configure('selectbackground')[4]) - printselected(node) - - def dynDeselected(self, node): - self.dCheckButton.configure(background = self.dLeaf.configure('background')[4]) - printdeselected(node) - - def ChkBtnHandler(self): - self.dLeaf.select() - if self.dyn.get() == 1: - self.dtree = dynamicTreeRootNode.insertbranch(label = 'Dynamic Tree Node', - selectcommand = printselected, - deselectcommand = printdeselected, - expandcommand = printexpanded, - collapsecommand = printcollapsed, - before = dynamicTreePosNode) - self.dtree.addleaf(label = 'Dynamic Leaf 1', - selectcommand = printselected, - deselectcommand = printdeselected) - self.dtree.addleaf(label = 'Dynamic Leaf 2', - selectcommand = printselected, - deselectcommand = printdeselected) - else: - if self.dtree != None: - dynamicTreeRootNode.delete(self.dtree) - self.dtree = None - - - foo = dynTree() - - - treeBrowser.pack(expand = 1, fill='both') - - exitButton = Tkinter.Button(rootWin, text="Quit", command=rootWin.quit) - exitButton.pack() - - rootWin.mainloop() diff --git a/Pmw/Pmw_1_2/demos/AboutDialog.py b/Pmw/Pmw_1_2/demos/AboutDialog.py deleted file mode 100644 index 1760befe..00000000 --- a/Pmw/Pmw_1_2/demos/AboutDialog.py +++ /dev/null @@ -1,43 +0,0 @@ -title = 'Pmw.AboutDialog demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - # Create dialog. - Pmw.aboutversion('9.9') - Pmw.aboutcopyright('Copyright My Company 1999\nAll rights reserved') - Pmw.aboutcontact( - 'For information about this application contact:\n' + - ' My Help Desk\n' + - ' Phone: +61 2 9876 5432\n' + - ' email: help@my.company.com.au' - ) - self.about = Pmw.AboutDialog(parent, applicationname = 'My Application') - self.about.withdraw() - - # Create button to launch the dialog. - w = Tkinter.Button(parent, text = 'Show about dialog', - command = self.execute) - w.pack(padx = 8, pady = 8) - - def execute(self): - self.about.show() - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/All.py b/Pmw/Pmw_1_2/demos/All.py deleted file mode 100755 index f94955cf..00000000 --- a/Pmw/Pmw_1_2/demos/All.py +++ /dev/null @@ -1,310 +0,0 @@ -#!/usr/bin/env python - -# ------------------------------------------------------------------ -# Display a splash screen as quickly as possible (before importing -# modules and initialising Pmw). - -import Tkinter -root = Tkinter.Tk(className = 'Demo') -root.withdraw() - -splash = Tkinter.Toplevel() -splash.withdraw() -splash.title('Welcome to the Pmw demos') -text = Tkinter.Label(splash, - font=('Helvetica', 16, 'bold'), - relief = 'raised', - borderwidth = 2, - padx=50, pady=50, - text = - 'Welcome to the Pmw megawidgets demo.\n' - '\n' - 'In a moment the main window will appear.\n' - 'Please enjoy yourself while you wait.\n' - 'You may be interested to know that splash screens\n' - '(as this window is called) were first devised to draw\n' - 'attention away from the fact the certain applications\n' - 'are slow to start. They are normally flashier and more\n' - 'entertaining than this one. This is a budget model.' -) -text.pack(fill = 'both', expand = 1) -splash.update_idletasks() - -width = splash.winfo_reqwidth() -height = splash.winfo_reqheight() -x = (root.winfo_screenwidth() - width) / 2 - root.winfo_vrootx() -y = (root.winfo_screenheight() - height) / 3 - root.winfo_vrooty() -if x < 0: - x = 0 -if y < 0: - y = 0 -geometry = '%dx%d+%d+%d' % (width, height, x, y) - -splash.geometry(geometry) -splash.update_idletasks() -splash.deiconify() -root.update() - -# ------------------------------------------------------------------ - -# Now crank up the application windows. - -import imp -import os -import re -import string -import sys -import types -import Tkinter -import DemoVersion -import Args - -# Find where the other scripts are, so they can be listed. -if __name__ == '__main__': - script_name = sys.argv[0] -else: - script_name = imp.find_module('DemoVersion')[1] - -script_name = os.path.normpath(script_name) -script_name = DemoVersion.expandLinks(script_name) -script_dir = os.path.dirname(script_name) -script_dir = DemoVersion.expandLinks(script_dir) - -# Add the '../../..' directory to the path. -package_dir = os.path.dirname(script_dir) -package_dir = DemoVersion.expandLinks(package_dir) -package_dir = os.path.dirname(package_dir) -package_dir = DemoVersion.expandLinks(package_dir) -package_dir = os.path.dirname(package_dir) -package_dir = DemoVersion.expandLinks(package_dir) -sys.path[:0] = [package_dir] - -# Import Pmw after modifying sys.path (it may not be in the default path). -import Pmw -DemoVersion.setPmwVersion() - -class Demo(Pmw.MegaWidget): - - def __init__(self, parent=None, **kw): - - # Define the megawidget options. - optiondefs = () - self.defineoptions(kw, optiondefs) - - # Initialise the base class (after defining the options). - Pmw.MegaWidget.__init__(self, parent) - - # Create the contents. - top = self.interior() - - panes = Pmw.PanedWidget(top, orient = 'horizontal') - panes.pack(fill = 'both', expand = 1) - - panes.add('widgetlist') - self._widgetlist = Pmw.ScrolledListBox(panes.pane('widgetlist'), - selectioncommand = Pmw.busycallback(self.startDemo), - label_text = 'Select a widget:', - labelpos = 'nw', - vscrollmode = 'dynamic', - hscrollmode = 'none', - listbox_exportselection = 0) - self._widgetlist.pack(fill = 'both', expand = 1, padx = 8) - - panes.add('info') - self._status = Tkinter.Label(panes.pane('info')) - self._status.pack(padx = 8, anchor = 'w') - - self._example = Tkinter.Frame(panes.pane('info'), - borderwidth = 2, - relief = 'sunken', - background = 'white') - self._example.pack(fill = 'both', expand = 1, padx = 8) - - self.buttonBox = Pmw.ButtonBox(top) - self.buttonBox.pack(fill = 'x') - - # Add the buttons and make them all the same width. - self._traceText = 'Trace tk calls' - self._stopTraceText = 'Stop trace' - self.buttonBox.add('Trace', text = self._traceText, - command = self.trace) - self.buttonBox.add('Code', text = 'Show code', command = self.showCode) - self.buttonBox.add('Exit', text = 'Exit', command = sys.exit) - self.buttonBox.alignbuttons() - - # Create the window to display the python code. - self.codeWindow = Pmw.TextDialog(parent, - title = 'Python source', - buttons = ('Dismiss',), - scrolledtext_labelpos = 'n', - label_text = 'Source') - self.codeWindow.withdraw() - self.codeWindow.insert('end', '') - - self.demoName = None - self._loadDemos() - - # Check keywords and initialise options. - self.initialiseoptions() - - def startDemo(self): - # Import the selected module and create and instance of the module's - # Demo class. - - sels = self._widgetlist.getcurselection() - if len(sels) == 0: - print 'No demonstrations to display' - return - demoName = sels[0] - - # Ignore if this if it is a sub title. - if demoName[0] != ' ': - self._widgetlist.bell() - return - - # Strip the leading two spaces. - demoName = demoName[2:] - - # Ignore if this demo is already being shown. - if self.demoName == demoName: - return - - self.demoName = demoName - - self.showStatus('Loading ' + demoName) - # Busy cursor - self.update_idletasks() - - for window in self._example.winfo_children(): - window.destroy() - - frame = Tkinter.Frame(self._example) - frame.pack(expand = 1) - exec 'import ' + demoName - # Need to keep a reference to the widget, so that variables, etc - # are not deleted. - self.widget = eval(demoName + '.Demo(frame)') - title = eval(demoName + '.title') - self.showStatus(title) - - if self.codeWindow.state() == 'normal': - self.insertCode() - - def showStatus(self, text): - self._status.configure(text = text) - - def showCode(self): - if self.codeWindow.state() != 'normal': - if self.demoName is None: - print 'No demonstration selected' - return - self.insertCode() - - self.codeWindow.show() - - def insertCode(self): - self.codeWindow.clear() - fileName = os.path.join(script_dir, self.demoName + '.py') - self.codeWindow.importfile(fileName) - self.codeWindow.configure(label_text = self.demoName + ' source') - - def trace(self): - text = self.buttonBox.component('Trace').cget('text') - if text == self._traceText: - self.buttonBox.configure(Trace_text = self._stopTraceText) - Pmw.tracetk(root, 1) - self.showStatus('Trace will appear on standard output') - else: - self.buttonBox.configure(Trace_text = self._traceText) - Pmw.tracetk(root, 0) - self.showStatus('Tk call tracing stopped') - - def _loadDemos(self): - files = os.listdir(script_dir) - files.sort() - megawidgets = [] - others = [] - for file in files: - if re.search('.py$', file) is not None and \ - file not in ['All.py', 'DemoVersion.py', 'Args.py']: - demoName = file[:-3] - index = string.find(demoName, '_') - if index < 0: - testattr = demoName - else: - testattr = demoName[:index] - if hasattr(Pmw, testattr): - megawidgets.append(demoName) - else: - others.append(demoName) - - self._widgetlist.insert('end', 'Megawidget demos:') - for name in megawidgets: - self._widgetlist.insert('end', ' ' + name) - self._widgetlist.insert('end', 'Other demos:') - for name in others: - self._widgetlist.insert('end', ' ' + name) - self._widgetlist.select_set(1) - -class StdOut: - def __init__(self, displayCommand): - self.displayCommand = displayCommand - self.text = '\n' - - def write(self, text): - if self.text[-1] == '\n': - self.text = text - else: - self.text = self.text + text - if self.text[-1] == '\n': - text = self.text[:-1] - else: - text = self.text - self.displayCommand(text) - -if os.name == 'nt': - defaultFontSize = 16 -else: - defaultFontSize = 12 - -commandLineArgSpecs = ( - ('fontscheme', 0, 'scheme', 'fonts to use [eg pmw2] (Tk defaults)'), - ('fontsize', 0, 'num', 'size of fonts to use with fontscheme', defaultFontSize), - ('stdout', 0, Args.Bool, 'print messages rather than display in label'), -) - -program = 'All.py' -msg = Args.parseArgs(program, sys.argv, commandLineArgSpecs, 0) -if msg is not None: - print msg - sys.exit() - -size = Args.get('fontsize') -fontScheme = Args.get('fontscheme') -Pmw.initialise(root, size = size, fontScheme = fontScheme, useTkOptionDb = 1) - -root.title('Pmw ' + Pmw.version() + ' megawidget demonstration') -if size < 18: - geometry = '800x550' -else: - geometry = '1000x700' -root.geometry(geometry) - -demo = Demo(root) -demo.pack(fill = 'both', expand = 1) -demo.focus() - -# Redirect standard output from demos to status line (unless -stdout -# option given on command line). -if not Args.get('stdout'): - sys.stdout = StdOut(demo.showStatus) - -# Start the first demo. -demo.startDemo() - -# Get rid of the splash screen -root.deiconify() -root.update() -splash.destroy() - -root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/Args.py b/Pmw/Pmw_1_2/demos/Args.py deleted file mode 100644 index 1bbedf91..00000000 --- a/Pmw/Pmw_1_2/demos/Args.py +++ /dev/null @@ -1,191 +0,0 @@ -"""Handle command line arguments. - -This module contains functions to parse and access the arguments given -to the program on the command line. -""" - -import types -import string -import sys - -# Symbolic constants for the indexes into an argument specifier tuple. -NAME = 0 -MANDATORY = 1 -TYPE = 2 -HELP = 3 -DEFAULT = 4 -SPEC_LENGTH = 5 - -Bool = [] - -helpSpec = ( - ('help', 0, Bool, 'print help and exit'), -) - -def parseArgs(title, argv, argSpecs, filesOK): - """Parse and check command line arguments. - - Scan the command line arguments in *argv* according to the argument - specifier *argSpecs*. Return **None** if there are no errors in - the arguments, otherwise return an error string describing the error. - - This function must be called to initialise this module. - - title -- The name of the program. This is used when returning - error messages or help text. - - argv -- A sequence containing the arguments given to the program. - Normally **sys.argv**. - - argSpecs -- A sequence of argument specifiers. Each specifier describes - a valid command line argument and consists of 4 or 5 items: - - - The argument name (without a leading minus sign **-**). - - - A boolean value, true if the argument is mandatory. - - - This should be **Args.Bool** if the argument has no option. - Otherwise it should be a string describing the option - required for this argument. This is used when printing help. - - - A short string describing the argument. - - - The default value of the argument. This should only be used - for non-mandatory arguments expecting an option. - - For example: - ( - ('foreground', 0, 'colour', 'colour of text', 'black'), - ('geometry', 0, 'spec', 'geometry of initial window'), - ('server', 1, 'ompserver', 'ompserver to connect to'), - ('silent', 0, Args.Bool, 'do not sound bell'), - ) - """ - - global programName - global _fileList - - errMsg = title + ' command line error: ' - programName = argv[0]; - - argSpecs = helpSpec + argSpecs - argSpecDic = {} - for spec in argSpecs: - arg = spec[NAME] - argSpecDic[arg] = spec - if len(spec) >= SPEC_LENGTH: - set(arg, spec[DEFAULT]) - elif spec[TYPE] is Bool: - set(arg, 0) - else: - set(arg, None) - - knownKeys = argSpecDic.keys() - - i = 1 - _fileList = [] - argc = len(argv) - while i < argc: - arg = argv[i] - key = arg[1:] - if key in knownKeys: - spec = argSpecDic[key] - if spec[TYPE] is Bool: - set(key, 1) - else: - i = i + 1 - if i >= argc: - return errMsg + 'missing argument to \'' + arg + '\' option.' - value = argv[i] - if len(spec) >= SPEC_LENGTH: - try: - if type(spec[DEFAULT]) == types.IntType: - typeStr = 'integer' - value = string.atoi(value) - elif type(spec[DEFAULT]) == types.FloatType: - typeStr = 'float' - value = string.atof(value) - except: - sys.exc_traceback = None # Clean up object references - return errMsg + 'cannot convert string \'' + value + \ - '\' to ' + typeStr + ' for option \'-' + key + '\'.' - set(key, value) - else: - _fileList.append(arg) - i = i + 1 - - if get('help'): - return _helpString(title, argSpecs) - - if not filesOK and len(_fileList) > 0: - if len(_fileList) == 1: - return errMsg + 'unknown option \'' + str(_fileList[0]) + '\'.' - else: - return errMsg + 'unknown options ' + str(_fileList) + '.' - - - _missing = [] - for spec in argSpecs: - if spec[MANDATORY] and get(spec[NAME]) is None: - _missing.append(spec[NAME]) - if len(_missing) == 1: - return errMsg + 'required argument \'-' + \ - str(_missing[0]) + '\' is missing.' - elif len(_missing) > 1: - return errMsg + 'required arguments ' + \ - str(map(lambda s: '-' + s, _missing)) + ' are missing.' - - return None - -def fileList(): - return _fileList - -def _helpString(title, argSpecs): - max = 0 - for spec in argSpecs: - if spec[TYPE] is Bool: - width = len(spec[NAME]) + 1 - else: - width = len(spec[NAME]) + 4 + len(spec[TYPE]) - if width > max: - max = width - - rtn = title + ' command line arguments:' - format = '\n %-' + str(max) + 's %s' - for mandatory in (1, 0): - needHeader = 1 - for spec in argSpecs: - if mandatory and spec[MANDATORY] or not mandatory and not spec[MANDATORY]: - if needHeader: - if mandatory: - rtn = rtn + '\n Mandatory arguments:' - else: - rtn = rtn + '\n Optional arguments (defaults in parentheses):' - needHeader = 0 - if spec[TYPE] is Bool: - arg = '-%s' % spec[NAME] - else: - arg = '-%s <%s>' % (spec[NAME], spec[TYPE]) - if len(spec) >= SPEC_LENGTH: - if type(spec[DEFAULT]) == types.StringType: - definition = spec[HELP] + ' (' + spec[DEFAULT] + ')' - else: - definition = spec[HELP] + ' (' + str(spec[DEFAULT]) + ')' - else: - definition = spec[HELP] - rtn = rtn + format % (arg, definition) - - return rtn - -def exists(key): - return configDict.has_key(key) - -def get(key): - return configDict[key] - -def set(key, value): - global configDict - - configDict[key] = value - -configDict = {} diff --git a/Pmw/Pmw_1_2/demos/Balloon.py b/Pmw/Pmw_1_2/demos/Balloon.py deleted file mode 100644 index 71788f64..00000000 --- a/Pmw/Pmw_1_2/demos/Balloon.py +++ /dev/null @@ -1,185 +0,0 @@ -title = 'Pmw.Balloon demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - # Create the Balloon. - self.balloon = Pmw.Balloon(parent) - - # Create some widgets and megawidgets with balloon help. - frame = Tkinter.Frame(parent) - frame.pack(padx = 10, pady = 5) - field = Pmw.EntryField(frame, - labelpos = 'nw', - label_text = 'Command:') - field.setentry('mycommand -name foo') - field.pack(side = 'left', padx = 10) - self.balloon.bind(field, 'Command to\nstart/stop', - 'Enter the shell command to control') - - start = Tkinter.Button(frame, text='Start') - start.pack(side='left', padx = 10) - self.balloon.bind(start, 'Start the command') - - stop = Tkinter.Button(frame, text='Stop') - stop.pack(side='left', padx = 10) - self.balloon.bind(stop, 'Stop the command') - - self.suicide = Tkinter.Button(frame, text='Kill me soon!', - command = self.killButton) - self.suicide.pack(side='left', padx = 10) - self.balloon.bind(self.suicide, 'Watch this button disappear!') - - scrolledCanvas = Pmw.ScrolledCanvas(parent, - canvas_width = 300, - canvas_height = 115, - ) - scrolledCanvas.pack() - canvas = scrolledCanvas.component('canvas') - self.canvas = canvas - - # Create some canvas items and individual help. - item = canvas.create_arc(5, 5, 35, 35, fill = 'red', extent = 315) - self.balloon.tagbind(canvas, item, 'This is help for\nan arc item') - item = canvas.create_bitmap(20, 150, bitmap = 'question') - self.balloon.tagbind(canvas, item, 'This is help for\na bitmap') - item = canvas.create_line(50, 60, 70, 80, 85, 20, width = 5) - self.balloon.tagbind(canvas, item, 'This is help for\na line item') - item = canvas.create_text(10, 90, text = 'Canvas items with balloons', - anchor = 'nw', font = field.cget('entry_font')) - self.balloon.tagbind(canvas, item, 'This is help for\na text item') - - # Create two canvas items which have the same tag and which use - # the same help. - canvas.create_rectangle(100, 10, 170, 50, fill = 'aliceblue', - tags = 'TAG1') - self.bluecircle = canvas.create_oval(110, 30, 160, 80, fill = 'blue', - tags = 'TAG1') - self.balloon.tagbind(canvas, 'TAG1', - 'This is help for the two blue items' + '\n' * 10 + - 'It is very, very big.', - 'This is help for the two blue items') - item = canvas.create_text(180, 10, text = 'Delete', - anchor = 'nw', font = field.cget('entry_font')) - self.balloon.tagbind(canvas, item, - 'After 2 seconds,\ndelete the blue circle') - canvas.tag_bind(item, '', self._canvasButtonpress) - scrolledCanvas.resizescrollregion() - - scrolledText = Pmw.ScrolledText(parent, - text_width = 32, - text_height = 4, - text_wrap = 'none', - ) - scrolledText.pack(pady = 5) - text = scrolledText.component('text') - self.text = text - - text.insert('end', - 'This is a text widget with ', '', - ' balloon', 'TAG1', - '\nhelp. Find the ', '', - ' text ', 'TAG1', - ' tagged with', '', - ' help.', 'TAG2', - '\n', '', - 'Remove tag 1.', 'TAG3', - '\nAnother line.\nAnd another', '', - ) - text.tag_configure('TAG1', borderwidth = 2, relief = 'sunken') - text.tag_configure('TAG3', borderwidth = 2, relief = 'raised') - - self.balloon.tagbind(text, 'TAG1', - 'There is one secret\nballoon help.\nCan you find it?') - self.balloon.tagbind(text, 'TAG2', - 'Well done!\nYou found it!') - self.balloon.tagbind(text, 'TAG3', - 'After 2 seconds\ndelete the tag') - text.tag_bind('TAG3', '', self._textButtonpress) - - frame = Tkinter.Frame(parent) - frame.pack(padx = 10) - self.toggleBalloonVar = Tkinter.IntVar() - self.toggleBalloonVar.set(1) - toggle = Tkinter.Checkbutton(frame, - variable = self.toggleBalloonVar, - text = 'Balloon help', command = self.toggle) - toggle.pack(side = 'left', padx = 10) - self.balloon.bind(toggle, 'Toggle balloon help\non and off') - - self.toggleStatusVar = Tkinter.IntVar() - self.toggleStatusVar.set(1) - toggle = Tkinter.Checkbutton(frame, - variable = self.toggleStatusVar, - text = 'Status help', command = self.toggle) - toggle.pack(side = 'left', padx = 10) - self.balloon.bind(toggle, - 'Toggle status help on and off, on and off' + '\n' * 10 + - 'It is very, very big, too.', - 'Toggle status help on and off') - - # Create and pack the MessageBar. - messageBar = Pmw.MessageBar(parent, - entry_width = 40, - entry_relief='groove', - labelpos = 'w', - label_text = 'Status:') - messageBar.pack(fill = 'x', expand = 1, padx = 10, pady = 5) - - # Configure the balloon to display its status messages in the - # message bar. - self.balloon.configure(statuscommand = messageBar.helpmessage) - - def toggle(self): - if self.toggleBalloonVar.get(): - if self.toggleStatusVar.get(): - self.balloon.configure(state = 'both') - else: - self.balloon.configure(state = 'balloon') - else: - if self.toggleStatusVar.get(): - self.balloon.configure(state = 'status') - else: - self.balloon.configure(state = 'none') - - def killButton(self): - # Test for old bug when destroying widgets 1) while the - # balloon was up and 2) during the initwait period. - print 'Destroying button in 2 seconds' - self.suicide.after(2000, self.suicide.destroy) - - def _canvasButtonpress(self, event): - print 'Destroying blue circle in 2 seconds' - self.canvas.after(2000, self.deleteBlueCircle) - - def deleteBlueCircle(self): - self.balloon.tagunbind(self.canvas, self.bluecircle) - self.canvas.delete(self.bluecircle) - - def _textButtonpress(self, event): - print 'Deleting the text tag in 2 seconds' - self.text.after(2000, self.deleteTextTag) - - def deleteTextTag(self): - self.balloon.tagunbind(self.text, 'TAG1') - self.text.tag_delete('TAG1') - - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root, 12, fontScheme = 'default') - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/BltGraph.py b/Pmw/Pmw_1_2/demos/BltGraph.py deleted file mode 100644 index a71c5c34..00000000 --- a/Pmw/Pmw_1_2/demos/BltGraph.py +++ /dev/null @@ -1,241 +0,0 @@ -title = 'Blt Graph demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import string -import Tkinter -import Pmw - -# Simple random number generator. -rand = 12345 -def random(): - global rand - rand = (rand * 125) % 2796203 - return rand - -class GraphDemo(Pmw.MegaToplevel): - - def __init__(self, parent=None, **kw): - - # Define the megawidget options. - optiondefs = ( - ('size', 10, Pmw.INITOPT), - ) - self.defineoptions(kw, optiondefs) - - # Initialise the base class (after defining the options). - Pmw.MegaToplevel.__init__(self, parent) - - # Create the graph. - self.createWidgets() - - # Check keywords and initialise options. - self.initialiseoptions() - - def createWidgets(self): - # Create vectors for use as x and y data points. - self._numElements = 7 - self._vectorSize = self['size'] - self._vector_x = Pmw.Blt.Vector() - self._vector_y = [] - for y in range(self._numElements): - self._vector_y.append(Pmw.Blt.Vector()) - for index in range(self._vectorSize): - self._vector_x.append(index) - for y in range(self._numElements): - self._vector_y[y].append(random() % 100) - - interior = self.interior() - - controlFrame = Tkinter.Frame(interior) - controlFrame.pack(side = 'bottom', fill = 'x', expand = 0) - - # Create an option menu for the kind of elements to create. - elementtype = Pmw.OptionMenu(controlFrame, - labelpos = 'nw', - label_text = 'Element type', - items = ['bars', 'lines', 'mixed', 'none'], - command = self._setelementtype, - menubutton_width = 8, - ) - elementtype.pack(side = 'left') - - # Create an option menu for the barmode option. - barmode = Pmw.OptionMenu(controlFrame, - labelpos = 'nw', - label_text = 'Bar mode', - items = ['normal', 'stacked', 'aligned', 'overlap'], - command = self._setbarmode, - menubutton_width = 8, - ) - barmode.pack(side = 'left') - - # Create an option menu for the smooth option. - self.smooth = Pmw.OptionMenu(controlFrame, - labelpos = 'nw', - label_text = 'Smooth', - items = ['linear', 'step', 'natural', 'quadratic'], - command = self._setsmooth, - menubutton_width = 9, - ) - self.smooth.pack(side = 'left') - - # Create an option menu to reverse sort the elements. - sortelements = Pmw.OptionMenu(controlFrame, - labelpos = 'nw', - label_text = 'Order', - items = ['normal', 'reverse'], - command = self._setsortelements, - menubutton_width = 8, - ) - sortelements.pack(side = 'left') - - # Create an option menu for the bufferelements option. - bufferelements = Pmw.OptionMenu(controlFrame, - labelpos = 'nw', - label_text = 'Buffering', - items = ['buffered', 'unbuffered'], - command = self._setbufferelements, - menubutton_width = 10, - ) - bufferelements.pack(side = 'left') - - # Create a button to add a point to the vector. - addpoint = Tkinter.Button(controlFrame, text = 'Add point', - command = Pmw.busycallback(self._addpoint)) - addpoint.pack(side = 'left', fill = 'x', expand = 0) - - # Create a button to close the window - close = Tkinter.Button(controlFrame, text = 'Close', - command = Pmw.busycallback(self.destroy)) - close.pack(side = 'left', fill = 'x', expand = 0) - - # Create the graph and its elements. - self._graph = Pmw.Blt.Graph(interior) - self._graph.pack(expand = 1, fill = 'both') - self._graph.yaxis_configure(command=self.yaxisCommand) - elementtype.invoke('mixed') - bufferelements.invoke('buffered') - - def yaxisCommand(self, graph, value): - try: - num = string.atoi(value) - return '%d %3d' % (num * 3, num) - except ValueError: - num = string.atof(value) - return '%g %3g' % (num * 3, num) - - def _setelementtype(self, type): - elements = self._graph.element_names() - apply(self._graph.element_delete, elements) - - if type == 'none': - return - - colorList = Pmw.Color.spectrum(self._numElements) - for elem in range(self._numElements): - if elem == 0: - hue = None - else: - hue = (elem + 1.0) / self._numElements * 6.28318 - foreground = colorList[elem] - background = Pmw.Color.changebrightness(self, foreground, 0.8) - if type == 'mixed': - if elem < self._numElements / 2: - bar = 0 - else: - bar = 1 - elif type == 'bars': - bar = 1 - else: - bar = 0 - if bar: - self._graph.bar_create( - 'var' + str(elem), - xdata=self._vector_x, - ydata=self._vector_y[elem], - foreground = foreground, - background = background) - else: - self._graph.line_create( - 'var' + str(elem), - linewidth = 4, - xdata=self._vector_x, - ydata=self._vector_y[elem], - smooth = self.smooth.getcurselection(), - color = foreground) - - def _setbarmode(self, tag): - self._graph.configure(barmode = tag) - - def _setsmooth(self, tag): - for element in self._graph.element_show(): - if self._graph.element_type(element) == 'line': - self._graph.element_configure(element, smooth = tag) - - def _setbufferelements(self, tag): - self._graph.configure(bufferelements = (tag == 'buffered')) - - def _setsortelements(self, tag): - element_list = list(self._graph.element_show()) - if len(element_list) > 1: - if (tag == 'normal') == (element_list[-1] != 'var0'): - element_list.reverse() - self._graph.element_show(element_list) - - def _addpoint(self): - self._vector_x.append(self._vectorSize) - for y in range(self._numElements): - self._vector_y[y].append(random() % 100) - self._vectorSize = self._vectorSize + 1 - -class Demo: - def __init__(self, parent): - if not Pmw.Blt.haveblt(parent): - message = 'Sorry\nThe BLT package has not been\n' + \ - 'installed on this system.\n' + \ - 'Please install it and try again.' - w = Tkinter.Label(parent, text = message) - w.pack(padx = 8, pady = 8) - return - - message = 'This is a simple demonstration of the\n' + \ - 'BLT graph widget.\n' + \ - 'Select the number of points to display and\n' + \ - 'click on the button to display the graph.' - w = Tkinter.Label(parent, text = message) - w.pack(padx = 8, pady = 8) - - # Create combobox to select number of points to display. - self.combo = Pmw.ComboBox(parent, - scrolledlist_items = ('10', '25', '50', '100', '300'), - entryfield_value = '10') - self.combo.pack(padx = 8, pady = 8) - - # Create button to start blt graph. - start = Tkinter.Button(parent, - text = 'Show BLT graph', - command = Pmw.busycallback(self.showGraphDemo)) - start.pack(padx = 8, pady = 8) - - self.parent = parent - - def showGraphDemo(self): - size = string.atoi(self.combo.get()) - demo = GraphDemo(self.parent, size = size) - demo.focus() - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/BltTabset.py b/Pmw/Pmw_1_2/demos/BltTabset.py deleted file mode 100644 index b6cf5894..00000000 --- a/Pmw/Pmw_1_2/demos/BltTabset.py +++ /dev/null @@ -1,101 +0,0 @@ -title = 'Blt Tabset demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - if not Pmw.Blt.haveblt(parent): - message = 'Sorry\nThe BLT package has not been\n' + \ - 'installed on this system.\n' + \ - 'Please install it and try again.' - w = Tkinter.Label(parent, text = message) - w.pack(padx = 8, pady = 8) - return - - self.tabset = Pmw.Blt.Tabset(parent, - borderwidth = 0, - highlightthickness = 0, - selectpad = 0, - tiers = 2, - ) - background = self.tabset.cget('background') - self.tabset.configure(selectbackground = background, - tabbackground = background, activebackground = background) - - configurePanel = Tkinter.Frame(self.tabset) - sideMenu = Pmw.OptionMenu (configurePanel, - labelpos = 'w', - label_text = 'Side:', - items = ('top', 'bottom', 'left', 'right'), - menubutton_width = 10, - command = self.changeSide, - ) - sideMenu.pack(anchor = 'w', padx = 10, pady = 10) - - rotateMenu = Pmw.ComboBox(configurePanel, - labelpos = 'w', - label_text = 'Text rotation:', - entryfield_validate = 'integer', - entry_width = 8, - selectioncommand = self.rotateText, - scrolledlist_items = (0, 45, 90, 135, 180, 225, 270, 315), - ) - rotateMenu.pack(side = 'left', padx = 10, pady = 10) - - rotateMenu.selectitem(0) - self.rotateText('0') - - self.appearancePanel = Tkinter.Label(self.tabset) - helpersPanel = Tkinter.Button(self.tabset, - text = 'This is a lot\nof help!') - - self.tabset.insert('end', - 'Appearance', 'Configure', 'Helpers', 'Images') - - self.tabset.tab_configure('Appearance', - command = self.appearance_cb, fill = 'both') - self.tabset.tab_configure('Configure', window = configurePanel) - self.tabset.tab_configure('Images', - command = self.images_cb, fill = 'both') - self.tabset.tab_configure('Helpers', - window = helpersPanel, padx = 100, pady = 150) - - self.tabset.invoke(1) - self.tabset.pack(fill = 'both', expand = 1, padx = 5, pady = 5) - self.tabset.focus() - - def appearance_cb(self): - self.appearancePanel.configure( - text = 'Don\'t judge a book\nby it\'s cover.') - self.tabset.tab_configure('Appearance', window = self.appearancePanel) - - def images_cb(self): - self.appearancePanel.configure(text = 'Beauty is only\nskin deep.') - self.tabset.tab_configure('Images', window = self.appearancePanel) - - def changeSide(self, side): - self.tabset.configure(side = side) - - def rotateText(self, angle): - if Pmw.integervalidator(angle) == Pmw.OK: - self.tabset.configure(rotate = angle) - else: - self.tabset.bell() - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/ButtonBox.py b/Pmw/Pmw_1_2/demos/ButtonBox.py deleted file mode 100644 index 984ff36f..00000000 --- a/Pmw/Pmw_1_2/demos/ButtonBox.py +++ /dev/null @@ -1,56 +0,0 @@ -title = 'Pmw.ButtonBox demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - # Create and pack the ButtonBox. - self.buttonBox = Pmw.ButtonBox(parent, - labelpos = 'nw', - label_text = 'ButtonBox:', - frame_borderwidth = 2, - frame_relief = 'groove') - self.buttonBox.pack(fill = 'both', expand = 1, padx = 10, pady = 10) - - # Add some buttons to the ButtonBox. - self.buttonBox.add('OK', command = self.ok) - self.buttonBox.add('Apply', command = self.apply) - self.buttonBox.add('Cancel', command = self.cancel) - - # Set the default button (the one executed when is hit). - self.buttonBox.setdefault('OK') - parent.bind('', self._processReturnKey) - parent.focus_set() - - # Make all the buttons the same width. - self.buttonBox.alignbuttons() - - def _processReturnKey(self, event): - self.buttonBox.invoke() - - def ok(self): - print 'You clicked on OK' - - def apply(self): - print 'You clicked on Apply' - - def cancel(self): - print 'You clicked on Cancel' - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/Colors.py b/Pmw/Pmw_1_2/demos/Colors.py deleted file mode 100644 index b6e0a5be..00000000 --- a/Pmw/Pmw_1_2/demos/Colors.py +++ /dev/null @@ -1,50 +0,0 @@ -title = 'Colorscheme demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - frame = Tkinter.Frame(parent) - frame.pack(fill = 'both', expand = 1) - - defaultPalette = Pmw.Color.getdefaultpalette(parent) - - colors = ('red', 'green', 'blue') - items = ('Testing', 'More testing', 'a test', 'foo', 'blah') - for count in range(len(colors)): - color = colors[count] - normalcolor = Pmw.Color.changebrightness(parent, color, 0.85) - Pmw.Color.setscheme(parent, normalcolor) - combo = Pmw.ComboBox(frame, - scrolledlist_items = items, - entryfield_value = items[0]) - combo.grid(sticky='nsew', row = count, column = 0) - - normalcolor = Pmw.Color.changebrightness(parent, color, 0.35) - Pmw.Color.setscheme(parent, normalcolor, foreground = 'white') - combo = Pmw.ComboBox(frame, - scrolledlist_items = items, - entryfield_value = items[0]) - combo.grid(sticky='nsew', row = count, column = 1) - - apply(Pmw.Color.setscheme, (parent,), defaultPalette) - #normalcolor = Pmw.Color.changebrightness(parent, 'red', 0.85) - #Pmw.Color.setscheme(parent, normalcolor) - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/ComboBox.py b/Pmw/Pmw_1_2/demos/ComboBox.py deleted file mode 100644 index 461fc809..00000000 --- a/Pmw/Pmw_1_2/demos/ComboBox.py +++ /dev/null @@ -1,76 +0,0 @@ -title = 'Pmw.ComboBox demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - parent.configure(background = 'white') - - # Create and pack the widget to be configured. - self.target = Tkinter.Label(parent, - relief = 'sunken', - padx = 20, - pady = 20, - ) - self.target.pack(fill = 'x', padx = 8, pady = 8) - - # Create and pack the simple ComboBox. - words = ('Monti', 'Python', 'ik', 'den', 'Holie', 'Grailen', '(Bok)') - simple = Pmw.ComboBox(parent, - label_text = 'Simple ComboBox:', - labelpos = 'nw', - selectioncommand = self.changeText, - scrolledlist_items = words, - dropdown = 0, - ) - simple.pack(side = 'left', fill = 'both', - expand = 1, padx = 8, pady = 8) - - # Display the first text. - first = words[0] - simple.selectitem(first) - self.changeText(first) - - # Create and pack the dropdown ComboBox. - colours = ('cornsilk1', 'snow1', 'seashell1', 'antiquewhite1', - 'bisque1', 'peachpuff1', 'navajowhite1', 'lemonchiffon1', - 'ivory1', 'honeydew1', 'lavenderblush1', 'mistyrose1') - dropdown = Pmw.ComboBox(parent, - label_text = 'Dropdown ComboBox:', - labelpos = 'nw', - selectioncommand = self.changeColour, - scrolledlist_items = colours, - ) - dropdown.pack(side = 'left', anchor = 'n', - fill = 'x', expand = 1, padx = 8, pady = 8) - - # Display the first colour. - first = colours[0] - dropdown.selectitem(first) - self.changeColour(first) - - def changeColour(self, colour): - print 'Colour: ' + colour - self.target.configure(background = colour) - - def changeText(self, text): - print 'Text: ' + text - self.target.configure(text = text) - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/ComboBoxDialog.py b/Pmw/Pmw_1_2/demos/ComboBoxDialog.py deleted file mode 100644 index c0e3deda..00000000 --- a/Pmw/Pmw_1_2/demos/ComboBoxDialog.py +++ /dev/null @@ -1,44 +0,0 @@ -title = 'Pmw.ComboBoxDialog demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - # Create the dialog. - self.dialog = Pmw.ComboBoxDialog(parent, - title = 'My ComboBoxDialog', - buttons = ('OK', 'Cancel'), - defaultbutton = 'OK', - combobox_labelpos = 'n', - label_text = 'What do you think of Pmw?', - scrolledlist_items = ('Cool man', 'Cool', 'Good', 'Bad', 'Gross')) - self.dialog.withdraw() - - # Create button to launch the dialog. - w = Tkinter.Button(parent, - text = 'Show combo box dialog', - command = self.doit) - w.pack(padx = 8, pady = 8) - - def doit(self): - result = self.dialog.activate() - print 'You clicked on', result, self.dialog.get() - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() - diff --git a/Pmw/Pmw_1_2/demos/ConfigClass.py b/Pmw/Pmw_1_2/demos/ConfigClass.py deleted file mode 100644 index b4d2b7fd..00000000 --- a/Pmw/Pmw_1_2/demos/ConfigClass.py +++ /dev/null @@ -1,76 +0,0 @@ -title = 'Component python class configuration demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class MyButton(Tkinter.Button): - # This is just an ordinary button with special colors. - - def __init__(self, master=None, cnf={}, **kw): - self.__toggle = 0 - kw['background'] = 'green' - kw['activebackground'] = 'red' - apply(Tkinter.Button.__init__, (self, master, cnf), kw) - -class Demo: - def __init__(self, parent): - - # Create a title label: - label = Tkinter.Label(parent, - text = 'EntryFields with label components of specified type:') - label.pack(fill='x', expand=1, padx=10, pady=5) - - # Create and pack some EntryFields. - entries = [] - entry = Pmw.EntryField(parent, - labelpos = 'w', - label_text = 'Label' - ) - entry.pack(fill='x', expand=1, padx=10, pady=5) - entries.append(entry) - - entry = Pmw.EntryField(parent, - labelpos = 'w', - label_pyclass = Tkinter.Button, - label_text = 'Button' - ) - entry.pack(fill='x', expand=1, padx=10, pady=5) - entries.append(entry) - - entry = Pmw.EntryField(parent, - labelpos = 'w', - label_pyclass = MyButton, - label_text = 'Special button' - ) - entry.pack(fill='x', expand=1, padx=10, pady=5) - entries.append(entry) - - Pmw.alignlabels(entries) - - # Create and pack a ButtonBox. - buttonBox = Pmw.ButtonBox(parent, - labelpos = 'nw', - label_text = 'ButtonBox:') - buttonBox.pack(fill = 'both', expand = 1, padx=10, pady=5) - - # Add some buttons to the ButtonBox. - buttonBox.add('with a') - buttonBox.add('special', pyclass = MyButton) - buttonBox.add('button') - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/Counter.py b/Pmw/Pmw_1_2/demos/Counter.py deleted file mode 100644 index 856b4dfa..00000000 --- a/Pmw/Pmw_1_2/demos/Counter.py +++ /dev/null @@ -1,121 +0,0 @@ -title = 'Pmw.Counter demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import string -import time -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - # Need to use long ints here because on the Macintosh the maximum size - # of an integer is smaller than the value returned by time.time(). - now = (long(time.time()) / 300) * 300 - - # Create the Counters. - self._date = Pmw.Counter(parent, - labelpos = 'w', - label_text = 'Date (4-digit year):', - entryfield_value = - time.strftime('%d/%m/%Y', time.localtime(now)), - entryfield_command = self.execute, - entryfield_validate = {'validator' : 'date', 'format' : 'dmy'}, - datatype = {'counter' : 'date', 'format' : 'dmy', 'yyyy' : 1}) - - self._isodate = Pmw.Counter(parent, - labelpos = 'w', - label_text = 'ISO-Date (4-digit year):', - entryfield_value = - time.strftime('%Y-%m-%d', time.localtime(now)), - entryfield_command = self.execute, - entryfield_validate = {'validator' : 'date', 'format' : 'ymd', - 'separator' : '-' }, - datatype = {'counter' : 'date', 'format' : 'ymd', 'yyyy' : 1, - 'separator' : '-' }) - - self._time = Pmw.Counter(parent, - labelpos = 'w', - label_text = 'Time:', - entryfield_value = - time.strftime('%H:%M:%S', time.localtime(now)), - entryfield_validate = {'validator' : 'time', - 'min' : '00:00:00', 'max' : '23:59:59', - 'minstrict' : 0, 'maxstrict' : 0}, - datatype = {'counter' : 'time', 'time24' : 1}, - increment=5*60) - self._real = Pmw.Counter(parent, - labelpos = 'w', - label_text = 'Real (with comma)\nand extra\nlabel lines:', - label_justify = 'left', - entryfield_value = '1,5', - datatype = {'counter' : 'real', 'separator' : ','}, - entryfield_validate = {'validator' : 'real', - 'min' : '-2,0', 'max' : '5,0', - 'separator' : ','}, - increment = 0.1) - self._custom = Pmw.Counter(parent, - labelpos = 'w', - label_text = 'Custom:', - entryfield_value = specialword[:4], - datatype = _custom_counter, - entryfield_validate = _custom_validate) - self._int = Pmw.Counter(parent, - labelpos = 'w', - label_text = 'Vertical integer:', - orient = 'vertical', - entry_width = 2, - entryfield_value = 50, - entryfield_validate = {'validator' : 'integer', - 'min' : 0, 'max' : 99} - ) - - counters = (self._date, self._isodate, self._time, self._real, - self._custom) - Pmw.alignlabels(counters) - - # Pack them all. - for counter in counters: - counter.pack(fill='both', expand=1, padx=10, pady=5) - self._int.pack(padx=10, pady=5) - - def execute(self): - print 'Return pressed, value is', self._date.get() - -specialword = 'Monti Python ik den Holie Grailen (Bok)' - -def _custom_validate(text): - if string.find(specialword, text) == 0: - return 1 - else: - return -1 - -def _custom_counter(text, factor, increment): - # increment is ignored here. - if string.find(specialword, text) == 0: - length = len(text) - if factor == 1: - if length >= len(specialword): - raise ValueError, 'maximum length reached' - return specialword[:length + 1] - else: - if length == 0: - raise ValueError, 'empty string' - return specialword[:length - 1] - else: - raise ValueError, 'bad string ' + text - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/CounterDialog.py b/Pmw/Pmw_1_2/demos/CounterDialog.py deleted file mode 100644 index 808c3bf3..00000000 --- a/Pmw/Pmw_1_2/demos/CounterDialog.py +++ /dev/null @@ -1,60 +0,0 @@ -title = 'Pmw.CounterDialog demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import string -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - # Create the dialog to prompt for the number of times to ring the bell. - self.dialog = Pmw.CounterDialog(parent, - label_text = 'Enter the number of times to\n' + \ - 'sound the bell (1 to 5)\n', - counter_labelpos = 'n', - entryfield_value = 2, - counter_datatype = 'numeric', - entryfield_validate = - {'validator' : 'numeric', 'min' : 1, 'max' : 5}, - buttons = ('OK', 'Cancel'), - defaultbutton = 'OK', - title = 'Bell ringing', - command = self.execute) - self.dialog.withdraw() - - # Create button to launch the dialog. - w = Tkinter.Button(parent, text = 'Show counter dialog', - command = self.dialog.activate) - w.pack(padx = 8, pady = 8) - - def execute(self, result): - if result is None or result == 'Cancel': - print 'Bell ringing cancelled' - self.dialog.deactivate() - else: - count = self.dialog.get() - if not self.dialog.valid(): - print 'Invalid entry: "' + count + '"' - else: - print 'Ringing the bell ' + count + ' times' - for num in range(string.atoi(count)): - if num != 0: - self.dialog.after(200) - self.dialog.bell() - self.dialog.deactivate() - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/DemoVersion.py b/Pmw/Pmw_1_2/demos/DemoVersion.py deleted file mode 100644 index 477a9f95..00000000 --- a/Pmw/Pmw_1_2/demos/DemoVersion.py +++ /dev/null @@ -1,36 +0,0 @@ -# Set the version of Pmw to use for the demonstrations based on the -# directory name. - -import imp -import os -import string - -def expandLinks(path): - if not os.path.isabs(path): - path = os.path.join(os.getcwd(), path) - while 1: - if not os.path.islink(path): - break - dir = os.path.dirname(path) - path = os.path.join(dir, os.readlink(path)) - - return path - -def setPmwVersion(): - file = imp.find_module(__name__)[1] - file = os.path.normpath(file) - file = expandLinks(file) - - dir = os.path.dirname(file) - dir = expandLinks(dir) - dir = os.path.dirname(dir) - dir = expandLinks(dir) - dir = os.path.basename(dir) - - version = string.replace(dir[4:], '_', '.') - import Pmw - if version in Pmw.installedversions(): - Pmw.setversion(version) - else: - print 'No such Pmw version', `version` + '.', - print 'Using default version', `Pmw.version()` diff --git a/Pmw/Pmw_1_2/demos/Dialog.py b/Pmw/Pmw_1_2/demos/Dialog.py deleted file mode 100644 index 3be3fdb0..00000000 --- a/Pmw/Pmw_1_2/demos/Dialog.py +++ /dev/null @@ -1,89 +0,0 @@ -title = 'Pmw.Dialog demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - # Create two buttons to launch the dialog. - w = Tkinter.Button(parent, text = 'Show application modal dialog', - command = self.showAppModal) - w.pack(padx = 8, pady = 8) - - w = Tkinter.Button(parent, text = 'Show global modal dialog', - command = self.showGlobalModal) - w.pack(padx = 8, pady = 8) - - w = Tkinter.Button(parent, text = 'Show dialog with "no grab"', - command = self.showDialogNoGrab) - w.pack(padx = 8, pady = 8) - - w = Tkinter.Button(parent, text = - 'Show toplevel window which\n' + - 'will not get a busy cursor', - command = self.showExcludedWindow) - w.pack(padx = 8, pady = 8) - - # Create the dialog. - self.dialog = Pmw.Dialog(parent, - buttons = ('OK', 'Apply', 'Cancel', 'Help'), - defaultbutton = 'OK', - title = 'My dialog', - command = self.execute) - self.dialog.withdraw() - - # Add some contents to the dialog. - w = Tkinter.Label(self.dialog.interior(), - text = 'Pmw Dialog\n(put your widgets here)', - background = 'black', - foreground = 'white', - pady = 20) - w.pack(expand = 1, fill = 'both', padx = 4, pady = 4) - - # Create the window excluded from showbusycursor. - self.excluded = Pmw.MessageDialog(parent, - title = 'I still work', - message_text = - 'This window will not get\n' + - 'a busy cursor when modal dialogs\n' + - 'are activated. In addition,\n' + - 'you can still interact with\n' + - 'this window when a "no grab"\n' + - 'modal dialog is displayed.') - self.excluded.withdraw() - Pmw.setbusycursorattributes(self.excluded.component('hull'), - exclude = 1) - - def showAppModal(self): - self.dialog.activate(geometry = 'centerscreenalways') - - def showGlobalModal(self): - self.dialog.activate(globalMode = 1) - - def showDialogNoGrab(self): - self.dialog.activate(globalMode = 'nograb') - - def showExcludedWindow(self): - self.excluded.show() - - def execute(self, result): - print 'You clicked on', result - if result not in ('Apply', 'Help'): - self.dialog.deactivate(result) - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/EntryField.py b/Pmw/Pmw_1_2/demos/EntryField.py deleted file mode 100644 index 69163816..00000000 --- a/Pmw/Pmw_1_2/demos/EntryField.py +++ /dev/null @@ -1,98 +0,0 @@ -title = 'Pmw.EntryField demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import time -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - # Create and pack the EntryFields. - self._any = Pmw.EntryField(parent, - labelpos = 'w', - label_text = 'Any:', - validate = None, - command = self.execute) - self._real = Pmw.EntryField(parent, - labelpos = 'w', - value = '55.5', - label_text = 'Real (10.0 to 99.0):', - validate = {'validator' : 'real', - 'min' : 10, 'max' : 99, 'minstrict' : 0}, - modifiedcommand = self.changed) - self._odd = Pmw.EntryField(parent, - labelpos = 'w', - label_text = 'Odd length:', - validate = self.custom_validate, - value = 'ABC') - self._date = Pmw.EntryField(parent, - labelpos = 'w', - label_text = 'Date (in 2000):', - value = '2000/2/29', - validate = {'validator' : 'date', - 'min' : '2000/1/1', 'max' : '2000/12/31', - 'minstrict' : 0, 'maxstrict' : 0, - 'format' : 'ymd'}, - ) - now = time.localtime(time.time()) - self._date2 = Pmw.EntryField(parent, - labelpos = 'w', - label_text = 'Date (d.m.y):', - value = '%d.%d.%d' % (now[2], now[1], now[0]), - validate = {'validator' : 'date', - 'format' : 'dmy', 'separator' : '.'}, - ) - self._time = Pmw.EntryField(parent, - labelpos = 'w', - label_text = 'Time (24hr clock):', - value = '8:00:00', - validate = {'validator' : 'time', - 'min' : '00:00:00', 'max' : '23:59:59', - 'minstrict' : 0, 'maxstrict' : 0}, - ) - self._comma = Pmw.EntryField(parent, - labelpos = 'w', - label_text = 'Real (with comma):', - value = '123,456', - validate = {'validator' : 'real', 'separator' : ','}, - ) - - entries = (self._any, self._real, self._odd, self._date, self._date2, - self._time, self._comma) - - for entry in entries: - entry.pack(fill='x', expand=1, padx=10, pady=5) - Pmw.alignlabels(entries) - - self._any.component('entry').focus_set() - - def changed(self): - print 'Text changed, value is', self._real.getvalue() - - def execute(self): - print 'Return pressed, value is', self._any.getvalue() - - # This implements a custom validation routine. It simply checks - # if the string is of odd length. - def custom_validate(self, text): - print 'text:', text - if len(text) % 2 == 0: - return -1 - else: - return 1 - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/ErrorHandling.py b/Pmw/Pmw_1_2/demos/ErrorHandling.py deleted file mode 100644 index 41fd10fc..00000000 --- a/Pmw/Pmw_1_2/demos/ErrorHandling.py +++ /dev/null @@ -1,42 +0,0 @@ -title = 'Pmw error handling demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import string -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - # Create two buttons to generate errors. - w = Tkinter.Button(parent, text = 'Click here to generate\n' + - 'an error in a command callback.', command = self.execute) - w.pack(padx = 8, pady = 8) - - w = Tkinter.Button(parent, text = 'Click here to generate\n' + - 'an error in a callback called\nfrom an event binding.') - w.pack(padx = 8, pady = 8) - w.bind('', self.execute) - w.bind('', self.execute) - - def execute(self, event = None): - self._error() - - def _error(self): - # Divide by zero - 1/0 - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/ExampleDemo.py b/Pmw/Pmw_1_2/demos/ExampleDemo.py deleted file mode 100644 index f7ec1e71..00000000 --- a/Pmw/Pmw_1_2/demos/ExampleDemo.py +++ /dev/null @@ -1,33 +0,0 @@ -title = 'Pmw.EXAMPLE demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - - # Create and pack the EXAMPLEs. - self.widget1 = Pmw.Counter(parent) - self.widget1.setentry('1') - self.widget1.pack() - - self.widget2 = Pmw.Counter(parent, increment = 10) - self.widget2.setentry('100') - self.widget2.pack() - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/Grid.py b/Pmw/Pmw_1_2/demos/Grid.py deleted file mode 100644 index 051863e5..00000000 --- a/Pmw/Pmw_1_2/demos/Grid.py +++ /dev/null @@ -1,44 +0,0 @@ -title = 'Grid geometry manager demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - frame = Tkinter.Frame(parent) - frame.pack(fill = 'both', expand = 1) - - button = {} - for num in range(0, 10): - button[num] = Tkinter.Button(frame, text = 'Button ' + str(num)) - - button[0].grid(column=0, row=0, rowspan=2, sticky='nsew') - button[1].grid(column=1, row=0, columnspan=3, sticky='nsew') - button[2].grid(column=1, row=1, rowspan=2, sticky='nsew') - button[3].grid(column=2, row=1) - button[4].grid(column=3, row=1) - button[5].grid(column=0, row=2) - button[6].grid(column=0, row=3, columnspan=2, sticky='nsew') - button[7].grid(column=2, row=2, columnspan=2, rowspan=2, sticky='nsew') - button[8].grid(column=0, row=4) - button[9].grid(column=3, row=4, sticky='e') - - frame.grid_rowconfigure(3, weight=1) - frame.grid_columnconfigure(3, weight=1) - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/Group.py b/Pmw/Pmw_1_2/demos/Group.py deleted file mode 100644 index b1c4ed5c..00000000 --- a/Pmw/Pmw_1_2/demos/Group.py +++ /dev/null @@ -1,93 +0,0 @@ -title = 'Pmw.Group demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - - # Create and pack the Groups. - w = Pmw.Group(parent, tag_text='label') - w.pack(fill = 'both', expand = 1, padx = 6, pady = 6) - cw = Tkinter.Label(w.interior(), - text = 'A group with the\ndefault Label tag') - cw.pack(padx = 2, pady = 2, expand='yes', fill='both') - - w = Pmw.Group(parent, tag_pyclass = None) - w.pack(fill = 'both', expand = 1, padx = 6, pady = 6) - cw = Tkinter.Label(w.interior(), text = 'A group\nwithout a tag') - cw.pack(padx = 2, pady = 2, expand='yes', fill='both') - - radiogroups = [] - self.var = Tkinter.IntVar() - self.var.set(0) - radioframe = Tkinter.Frame(parent) - w = Pmw.Group(radioframe, - tag_pyclass = Tkinter.Radiobutton, - tag_text='radiobutton 1', - tag_value = 0, - tag_variable = self.var) - w.pack(fill = 'both', expand = 1, side='left') - cw = Tkinter.Frame(w.interior(),width=200,height=20) - cw.pack(padx = 2, pady = 2, expand='yes', fill='both') - radiogroups.append(w) - - w = Pmw.Group(radioframe, - tag_pyclass = Tkinter.Radiobutton, - tag_text='radiobutton 2', - tag_font = Pmw.logicalfont('Helvetica', 4), - tag_value = 1, - tag_variable = self.var) - w.pack(fill = 'both', expand = 1, side='left') - cw = Tkinter.Frame(w.interior(),width=200,height=20) - cw.pack(padx = 2, pady = 2, expand='yes', fill='both') - radiogroups.append(w) - radioframe.pack(padx = 6, pady = 6, expand='yes', fill='both') - Pmw.aligngrouptags(radiogroups) - - w = Pmw.Group(parent, - tag_pyclass = Tkinter.Checkbutton, - tag_text='checkbutton', - tag_foreground='blue') - w.pack(fill = 'both', expand = 1, padx = 6, pady = 6) - cw = Tkinter.Frame(w.interior(),width=150,height=20) - cw.pack(padx = 2, pady = 2, expand='yes', fill='both') - - w = Pmw.Group(parent, - tag_pyclass = Tkinter.Button, - tag_text='Tkinter.Button') - w.configure(tag_command = w.toggle) - w.pack(fill = 'both', expand = 1, padx = 6, pady = 6) - cw = Tkinter.Label(w.interior(), - background = 'aliceblue', - text = 'A group with\na Button tag!?' - ) - cw.pack(padx = 2, pady = 2, expand='yes', fill='both') - - w = Pmw.Group(parent, - tag_pyclass = Tkinter.Button, - tag_text='Show/Hide') - w.configure(tag_command = w.toggle) - w.pack(fill = 'both', expand = 1, padx = 6, pady = 6) - cw = Tkinter.Label(w.interior(), - background = 'aliceblue', - text = 'Now you see me.\nNow you don\'t.' - ) - cw.pack(padx = 2, pady = 2, expand='yes', fill='both') - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/HistoryText.py b/Pmw/Pmw_1_2/demos/HistoryText.py deleted file mode 100644 index 5a7b2eb4..00000000 --- a/Pmw/Pmw_1_2/demos/HistoryText.py +++ /dev/null @@ -1,102 +0,0 @@ -title = 'Pmw.HistoryText demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - # Create and pack the PanedWidget to hold the query and result - # windows. - # !! panedwidget should automatically size to requested size - panedWidget = Pmw.PanedWidget(parent, - orient = 'vertical', - hull_height = 400, - hull_width = 550) - panedWidget.add('query', min = 0.05, size = 0.2) - panedWidget.add('buttons', min = 0.1, max = 0.1) - panedWidget.add('results', min = 0.05) - panedWidget.pack(fill = 'both', expand = 1) - - # Create and pack the HistoryText. - self.historyText = Pmw.HistoryText(panedWidget.pane('query'), - text_wrap = 'none', - text_width = 60, - text_height = 10, - historycommand = self.statechange, - ) - self.historyText.pack(fill = 'both', expand = 1) - self.historyText.component('text').focus() - - buttonList = ( - [20, None], - ['Clear', self.clear], - ['Undo', self.historyText.undo], - ['Redo', self.historyText.redo], - [20, None], - ['Prev', self.historyText.prev], - ['Next', self.historyText.next], - [30, None], - ['Execute', Pmw.busycallback(self.executeQuery)], - ) - self.buttonDict = {} - - buttonFrame = panedWidget.pane('buttons') - for text, cmd in buttonList: - if type(text) == type(69): - frame = Tkinter.Frame(buttonFrame, width = text) - frame.pack(side = 'left') - else: - button = Tkinter.Button(buttonFrame, text = text, command = cmd) - button.pack(side = 'left') - self.buttonDict[text] = button - - for text in ('Prev', 'Next'): - self.buttonDict[text].configure(state = 'disabled') - - self.results = Pmw.ScrolledText(panedWidget.pane('results'), text_wrap = 'none') - self.results.pack(fill = 'both', expand = 1) - - def statechange(self, prevstate, nextstate): - self.buttonDict['Prev'].configure(state = prevstate) - self.buttonDict['Next'].configure(state = nextstate) - - def clear(self): - self.historyText.delete('1.0', 'end') - - def addnewlines(self, text): - if len(text) == 1: - text = text + '\n' - if text[-1] != '\n': - text = text + '\n' - if text[-2] != '\n': - text = text + '\n' - return text - - def executeQuery(self): - sql = self.historyText.get() - self.results.insert('end', 'Query:\n' + self.addnewlines(sql)) - self.results.see('end') - self.results.update_idletasks() - self.historyText.addhistory() - results = 'Results:\nfoo' - if len(results) > 0: - self.results.insert('end', self.addnewlines(results)) - self.results.see('end') - - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/LabeledWidget.py b/Pmw/Pmw_1_2/demos/LabeledWidget.py deleted file mode 100644 index 8a98c59e..00000000 --- a/Pmw/Pmw_1_2/demos/LabeledWidget.py +++ /dev/null @@ -1,46 +0,0 @@ -title = 'Pmw.LabeledWidget demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - - # Create a frame to put the LabeledWidgets into - frame = Tkinter.Frame(parent, background = 'grey90') - frame.pack(fill = 'both', expand = 1) - - # Create and pack the LabeledWidgets. - column = 0 - row = 0 - for pos in ('n', 'nw', 'wn', 'w'): - lw = Pmw.LabeledWidget(frame, - labelpos = pos, - label_text = pos + ' label') - lw.component('hull').configure(relief='sunken', borderwidth=2) - lw.grid(column=column, row=row, padx=10, pady=10) - cw = Tkinter.Button(lw.interior(), text='child\nsite') - cw.pack(padx=10, pady=10, expand='yes', fill='both') - - # Get ready for next grid position. - column = column + 1 - if column == 2: - column = 0 - row = row + 1 - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - widget = Demo(root) - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack() - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/LogicalFont.py b/Pmw/Pmw_1_2/demos/LogicalFont.py deleted file mode 100644 index 61854690..00000000 --- a/Pmw/Pmw_1_2/demos/LogicalFont.py +++ /dev/null @@ -1,84 +0,0 @@ -title = 'Pmw LogicalFont demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import string -import Tkinter -import Pmw - -class Demo: - - # The fonts to demonstrate. - fontList = ( - (('Times', 0), {}), - (('Helvetica', 0), {}), - (('Typewriter', 0), {}), - (('Fixed', 0), {}), - (('Courier', 0), {}), - (('Helvetica', 2), {'slant' : 'italic'}), - (('Helvetica', 0), {'size' : 18}), - (('Helvetica', 0), {'weight' : 'bold'}), - (('Helvetica', 12), {'weight' : 'bold', 'slant' : 'italic'}), - (('Typewriter', 0), {'size' : 8, 'weight' : 'bold'}), - (('Fixed', 0), {'size' : 8, 'weight' : 'bold'}), - (('Times', 0), {'size' : 24, 'weight' : 'bold', 'slant' : 'italic'}), - (('Typewriter', 0), {'width' : 'condensed'}), - (('Typewriter', -1), {'width' : 'condensed'}), - (('Fixed', 0), {'width' : 'condensed'}), - (('Fixed', -1), {'width' : 'condensed'}), - (('Helvetica', 0), {'weight' : 'bogus'}), - ) - - fontText = [] - - def __init__(self, parent): - - self.parent = parent - - # Create the text to display to the user to represent each font. - if Demo.fontText == []: - for args, dict in Demo.fontList: - text = args[0] - if args[1] != 0: - text = text + ' ' + str(args[1]) - for name, value in dict.items(): - text = text + ' ' + name + ': ' + str(value) - Demo.fontText.append(text) - - # Create a listbox to contain the font selections. - self.box = Pmw.ScrolledListBox(parent, listbox_selectmode='single', - listbox_width = 35, - listbox_height = 10, - items=Demo.fontText, - label_text='Font', labelpos='nw', - selectioncommand=self.selectionCommand) - self.box.pack(fill = 'both', expand = 1, padx = 10, pady = 10) - - # Create a label to display the selected font. - self.target = Tkinter.Label(parent, - text = 'The quick brown fox jumps\nover the lazy dog', - relief = 'sunken', padx = 10, pady = 10) - self.target.pack(fill = 'both', expand = 1, padx = 10, pady = 10) - - def selectionCommand(self): - sel = self.box.curselection() - if len(sel) > 0: - args, dict = Demo.fontList[string.atoi(sel[0])] - font = apply(Pmw.logicalfont, args, dict) - self.target.configure(font = font) - print font - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/MainMenuBar.py b/Pmw/Pmw_1_2/demos/MainMenuBar.py deleted file mode 100644 index 682d36ee..00000000 --- a/Pmw/Pmw_1_2/demos/MainMenuBar.py +++ /dev/null @@ -1,176 +0,0 @@ -title = 'Pmw.MainMenuBar demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - # Create button to launch the toplevel with main menubar. - w = Tkinter.Button(parent, text = 'Show Pmw.MainMenuBar demo', - command = lambda parent=parent: MainMenuBarToplevel(parent)) - w.pack(padx = 8, pady = 8) - -class MainMenuBarToplevel: - def __init__(self, parent): - # Create the toplevel to contain the main menubar. - megaToplevel = Pmw.MegaToplevel(parent, title = title) - toplevel = megaToplevel.interior() - - # Create the Balloon for this toplevel. - self.balloon = Pmw.Balloon(toplevel) - - # Create and install the MenuBar. - menuBar = Pmw.MainMenuBar(toplevel, - balloon = self.balloon) - toplevel.configure(menu = menuBar) - self.menuBar = menuBar - - # Add some buttons to the MainMenuBar. - menuBar.addmenu('File', 'Close this window or exit') - menuBar.addmenuitem('File', 'command', 'Close this window', - command = PrintOne('Action: close'), - label = 'Close') - menuBar.addmenuitem('File', 'separator') - menuBar.addmenuitem('File', 'command', 'Exit the application', - command = PrintOne('Action: exit'), - label = 'Exit') - - menuBar.addmenu('Edit', 'Cut, copy or paste') - menuBar.addmenuitem('Edit', 'command', 'Delete the current selection', - command = PrintOne('Action: delete'), - label = 'Delete') - - menuBar.addmenu('Options', 'Set user preferences') - menuBar.addmenuitem('Options', 'command', 'Set general preferences', - command = PrintOne('Action: general options'), - label = 'General...') - - # Create a checkbutton menu item. - self.toggleVar = Tkinter.IntVar() - # Initialise the checkbutton to 1: - self.toggleVar.set(1) - menuBar.addmenuitem('Options', 'checkbutton', 'Toggle me on/off', - label = 'Toggle', - command = self._toggleMe, - variable = self.toggleVar) - self._toggleMe() - - menuBar.addcascademenu('Options', 'Size', - 'Set some other preferences', traverseSpec = 'z', tearoff = 1) - for size in ('tiny', 'small', 'average', 'big', 'huge'): - menuBar.addmenuitem('Size', 'command', 'Set size to ' + size, - command = PrintOne('Action: size ' + size), - label = size) - - menuBar.addmenu('Help', 'User manuals', name = 'help') - menuBar.addmenuitem('Help', 'command', 'About this application', - command = PrintOne('Action: about'), - label = 'About...') - - # Create and pack the main part of the window. - self.mainPart = Tkinter.Label(toplevel, - text = 'This is the\nmain part of\nthe window', - background = 'black', - foreground = 'white', - padx = 30, - pady = 30) - self.mainPart.pack(fill = 'both', expand = 1) - - # Create and pack the MessageBar. - self.messageBar = Pmw.MessageBar(toplevel, - entry_width = 40, - entry_relief='groove', - labelpos = 'w', - label_text = 'Status:') - self.messageBar.pack(fill = 'x', padx = 10, pady = 10) - self.messageBar.message('state', - 'Balloon/status help not working properly - Tk menubar bug') - - buttonBox = Pmw.ButtonBox(toplevel) - buttonBox.pack(fill = 'x') - buttonBox.add('Disable\nall', command = menuBar.disableall) - buttonBox.add('Enable\nall', command = menuBar.enableall) - buttonBox.add('Create\nmenu', command = self.add) - buttonBox.add('Delete\nmenu', command = self.delete) - buttonBox.add('Create\nitem', command = self.additem) - buttonBox.add('Delete\nitem', command = self.deleteitem) - - # Configure the balloon to displays its status messages in the - # message bar. - self.balloon.configure(statuscommand = self.messageBar.helpmessage) - - self.testMenuList = [] - - def _toggleMe(self): - print 'Toggle value:', self.toggleVar.get() - - def add(self): - if len(self.testMenuList) == 0: - num = 0 - else: - num = self.testMenuList[-1] - num = num + 1 - name = 'Menu%d' % num - self.testMenuList.append(num) - - self.menuBar.addmenu(name, 'This is ' + name) - - def delete(self): - if len(self.testMenuList) == 0: - self.menuBar.bell() - else: - num = self.testMenuList[0] - name = 'Menu%d' % num - del self.testMenuList[0] - self.menuBar.deletemenu(name) - - def additem(self): - if len(self.testMenuList) == 0: - self.menuBar.bell() - else: - num = self.testMenuList[-1] - menuName = 'Menu%d' % num - menu = self.menuBar.component(menuName) - if menu.index('end') is None: - label = 'item X' - else: - label = menu.entrycget('end', 'label') + 'X' - self.menuBar.addmenuitem(menuName, 'command', 'Help for ' + label, - command = PrintOne('Action: ' + menuName + ': ' + label), - label = label) - - def deleteitem(self): - if len(self.testMenuList) == 0: - self.menuBar.bell() - else: - num = self.testMenuList[-1] - menuName = 'Menu%d' % num - menu = self.menuBar.component(menuName) - if menu.index('end') is None: - self.menuBar.bell() - else: - self.menuBar.deletemenuitems(menuName, 0) - -class PrintOne: - def __init__(self, text): - self.text = text - - def __call__(self): - print self.text - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/MenuBar.py b/Pmw/Pmw_1_2/demos/MenuBar.py deleted file mode 100644 index 8e22e53b..00000000 --- a/Pmw/Pmw_1_2/demos/MenuBar.py +++ /dev/null @@ -1,166 +0,0 @@ -title = 'Pmw.MenuBar demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - # Create the Balloon. - self.balloon = Pmw.Balloon(parent) - - # Create and pack the MenuBar. - menuBar = Pmw.MenuBar(parent, - hull_relief = 'raised', - hull_borderwidth = 1, - balloon = self.balloon) - menuBar.pack(fill = 'x') - self.menuBar = menuBar - - # Add some buttons to the MenuBar. - menuBar.addmenu('File', 'Close this window or exit') - menuBar.addmenuitem('File', 'command', 'Close this window', - command = PrintOne('Action: close'), - label = 'Close') - menuBar.addmenuitem('File', 'separator') - menuBar.addmenuitem('File', 'command', 'Exit the application', - command = PrintOne('Action: exit'), - label = 'Exit') - - menuBar.addmenu('Edit', 'Cut, copy or paste') - menuBar.addmenuitem('Edit', 'command', 'Delete the current selection', - command = PrintOne('Action: delete'), - label = 'Delete') - - menuBar.addmenu('Options', 'Set user preferences') - menuBar.addmenuitem('Options', 'command', 'Set general preferences', - command = PrintOne('Action: general options'), - label = 'General...') - - # Create a checkbutton menu item. - self.toggleVar = Tkinter.IntVar() - # Initialise the checkbutton to 1: - self.toggleVar.set(1) - menuBar.addmenuitem('Options', 'checkbutton', 'Toggle me on/off', - label = 'Toggle', - command = self._toggleMe, - variable = self.toggleVar) - self._toggleMe() - - menuBar.addcascademenu('Options', 'Size', - 'Set some other preferences', traverseSpec = 'z', tearoff = 1) - for size in ('tiny', 'small', 'average', 'big', 'huge'): - menuBar.addmenuitem('Size', 'command', 'Set size to ' + size, - command = PrintOne('Action: size ' + size), - label = size) - - menuBar.addmenu('Help', 'User manuals', side = 'right') - menuBar.addmenuitem('Help', 'command', 'About this application', - command = PrintOne('Action: about'), - label = 'About...') - - # Create and pack the main part of the window. - self.mainPart = Tkinter.Label(parent, - text = 'This is the\nmain part of\nthe window', - background = 'black', - foreground = 'white', - padx = 30, - pady = 30) - self.mainPart.pack(fill = 'both', expand = 1) - - # Create and pack the MessageBar. - self.messageBar = Pmw.MessageBar(parent, - entry_width = 40, - entry_relief='groove', - labelpos = 'w', - label_text = 'Status:') - self.messageBar.pack(fill = 'x', padx = 10, pady = 10) - self.messageBar.message('state', 'OK') - - buttonBox = Pmw.ButtonBox(parent) - buttonBox.pack(fill = 'x') - buttonBox.add('Disable\nall', command = menuBar.disableall) - buttonBox.add('Enable\nall', command = menuBar.enableall) - buttonBox.add('Create\nmenu', command = self.add) - buttonBox.add('Delete\nmenu', command = self.delete) - buttonBox.add('Create\nitem', command = self.additem) - buttonBox.add('Delete\nitem', command = self.deleteitem) - - # Configure the balloon to displays its status messages in the - # message bar. - self.balloon.configure(statuscommand = self.messageBar.helpmessage) - - self.testMenuList = [] - - def _toggleMe(self): - print 'Toggle value:', self.toggleVar.get() - - def add(self): - if len(self.testMenuList) == 0: - num = 0 - else: - num = self.testMenuList[-1] - num = num + 1 - name = 'Menu%d' % num - self.testMenuList.append(num) - - self.menuBar.addmenu(name, 'This is ' + name) - - def delete(self): - if len(self.testMenuList) == 0: - self.menuBar.bell() - else: - num = self.testMenuList[0] - name = 'Menu%d' % num - del self.testMenuList[0] - self.menuBar.deletemenu(name) - - def additem(self): - if len(self.testMenuList) == 0: - self.menuBar.bell() - else: - num = self.testMenuList[-1] - menuName = 'Menu%d' % num - menu = self.menuBar.component(menuName + '-menu') - if menu.index('end') is None: - label = 'item X' - else: - label = menu.entrycget('end', 'label') + 'X' - self.menuBar.addmenuitem(menuName, 'command', 'Help for ' + label, - command = PrintOne('Action: ' + menuName + ': ' + label), - label = label) - - def deleteitem(self): - if len(self.testMenuList) == 0: - self.menuBar.bell() - else: - num = self.testMenuList[-1] - menuName = 'Menu%d' % num - menu = self.menuBar.component(menuName + '-menu') - if menu.index('end') is None: - self.menuBar.bell() - else: - self.menuBar.deletemenuitems(menuName, 0) - -class PrintOne: - def __init__(self, text): - self.text = text - - def __call__(self): - print self.text - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/MessageBar.py b/Pmw/Pmw_1_2/demos/MessageBar.py deleted file mode 100644 index 8cec7ddc..00000000 --- a/Pmw/Pmw_1_2/demos/MessageBar.py +++ /dev/null @@ -1,85 +0,0 @@ -title = 'Pmw.MessageBar demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - # Create and pack the MessageBar. - self._messagebar = Pmw.MessageBar(parent, - entry_width = 40, - entry_relief='groove', - labelpos = 'w', - label_text = 'Status:') - self._messagebar.pack(side = 'bottom', fill = 'x', - expand = 1, padx = 10, pady = 10) - - # Create and pack the ScrolledListBox to change the MessageBar. - self.box = Pmw.ScrolledListBox(parent, - listbox_selectmode='single', - items=('state', 'help', 'userevent', 'systemevent', - 'usererror', 'systemerror', 'busy',), - label_text='Message type', - labelpos='n', - selectioncommand=self.selectionCommand) - self.box.pack(fill = 'both', expand = 'yes', padx = 10, pady = 10) - - self._index = 0 - self._stateCounter = 0 - - def selectionCommand(self): - sels = self.box.getcurselection() - if len(sels) > 0: - self._index = self._index + 1 - messagetype = sels[0] - if messagetype == 'state': - self._stateCounter = (self._stateCounter + 1) % 3 - text = stateMessages[self._stateCounter] - if text != '': - text = text + ' (' + messagetype + ')' - self._messagebar.message('state', text) - else: - text = messages[messagetype] - text = text + ' (' + messagetype + ')' - self._messagebar.message(messagetype, text) - if messagetype == 'busy': - Pmw.showbusycursor() - self.box.after(2000) - Pmw.hidebusycursor() - self._messagebar.resetmessages('busy') - text = 'All files successfully removed' - text = text + ' (userevent)' - self._messagebar.message('userevent', text) - - -messages = { - 'help': 'Save current file', - 'userevent': 'Saving file "foo"', - 'busy': 'Busy deleting all files from file system ...', - 'systemevent': 'File "foo" saved', - 'usererror': 'Invalid file name "foo/bar"', - 'systemerror': 'Failed to save file: file system full', -} - -stateMessages = { - 0: '', - 1: 'Database is down', - 2: 'Waiting for reply from database', -} - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/MessageDialog.py b/Pmw/Pmw_1_2/demos/MessageDialog.py deleted file mode 100644 index 09c8c98b..00000000 --- a/Pmw/Pmw_1_2/demos/MessageDialog.py +++ /dev/null @@ -1,102 +0,0 @@ -title = 'Pmw.MessageDialog demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - self.parent = parent - - # Create dialog 1. - self.dialog1 = Pmw.MessageDialog(parent, - title = 'Simple message dialog', - defaultbutton = 0, - message_text = 'A simple message dialog\nwith no callback.') - self.dialog1.iconname('Simple message dialog') - self.dialog1.withdraw() - - # Create dialog 2. - self.dialog2 = Pmw.MessageDialog(parent, - title = 'Bell ringing dialog', - message_text = 'This message dialog\nwill ring the bell ' + - 'when\nyou click on the buttons.', - iconpos = 'w', - icon_bitmap = 'error', - command = self.execute2, - buttons = ('One', 'Two', 'Three', 'Close')) - self.dialog2.iconname('Bell ringing dialog') - self.dialog2.withdraw() - - # Create dialog 3. - self.dialog3 = Pmw.MessageDialog(parent, - title = 'Vertical button dialog', - message_text = 'This message dialog\nhas the buttons on the\n' + - 'right hand side.', - buttonboxpos = 'e', - iconpos = 'n', - icon_bitmap = 'warning', - buttons = ('Goodbye', 'Au revoir', 'Sayonara', 'Close'), - defaultbutton = 'Close') - self.dialog3.iconname('Vertical button dialog') - self.dialog3.withdraw() - - # Create some buttons to launch the dialogs. - w = Tkinter.Button(parent, text = 'Simple dialog', - command = lambda self = self: - self.dialog1.activate(geometry = 'first+100+100')) - w.pack(padx = 8, pady = 8) - - w = Tkinter.Button(parent, text = 'Bell ringing dialog', - command = self.dialog2.activate) - w.pack(padx = 8, pady = 8) - - w = Tkinter.Button(parent, text = 'Vertical buttons', - command = self.dialog3.activate) - w.pack(padx = 8, pady = 8) - - w = Tkinter.Button(parent, text = 'On the fly dialog', - command = self._createOnTheFly) - w.pack(padx = 8, pady = 8) - - def execute2(self, result): - print 'You clicked on', result - if result is None: - self.dialog2.deactivate(result) - elif result == 'Close': - self.dialog2.deactivate(result) - else: - for count in range({'One': 1, 'Two': 2, 'Three': 3}[result]): - if count != 0: - self.dialog2.after(200) - self.dialog2.bell() - - def _createOnTheFly(self): - dialog = Pmw.MessageDialog(self.parent, - title = 'On the fly dialog', - defaultbutton = 0, - buttons = ('OK', 'Apply', 'Cancel', 'Help'), - message_text = 'This dialog was created when you clicked ' + - 'on the button.') - dialog.iconname('Simple message dialog') - result = dialog.activate() - - print 'You selected', result - - - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/MessageInfo.py b/Pmw/Pmw_1_2/demos/MessageInfo.py deleted file mode 100644 index 1c2fac40..00000000 --- a/Pmw/Pmw_1_2/demos/MessageInfo.py +++ /dev/null @@ -1,108 +0,0 @@ -title = 'Pmw toplevel megawidget demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class MessageInfo(Pmw.MegaToplevel): - - # Demo Pmw toplevel megawidget. - - def __init__(self, parent=None, **kw): - - # Define the megawidget options. - optiondefs = () - self.defineoptions(kw, optiondefs) - - # Initialise the base class (after defining the options). - Pmw.MegaToplevel.__init__(self, parent) - - # Create the components. - interior = self.interior() - - self._dismiss = self.createcomponent('dismiss', - (), None, - Tkinter.Button, (interior,), - text = 'Dismiss', - command = self.goodbye) - self._dismiss.pack(side = 'bottom', pady = 4) - - self._separator = self.createcomponent('separator', - (), None, - Tkinter.Frame, (interior,), - height = 2, - borderwidth = 1, - relief = 'sunken') - self._separator.pack(side = 'bottom', fill = 'x', pady = 4) - - self._icon = self.createcomponent('icon', - (), None, - Tkinter.Label, (interior,)) - self._icon.pack(side = 'left', padx = 8, pady = 8) - - self._infoFrame = self.createcomponent('infoframe', - (), None, - Tkinter.Frame, (interior,)) - self._infoFrame.pack( - side = 'left', - fill = 'both', - expand = 1, - padx = 4, - pady = 4) - - self._message = self.createcomponent('message', - (), None, - Tkinter.Label, (interior,)) - self._message.pack(expand = 1, fill = 'both', padx = 10, pady = 10) - - self.bind('', self.goodbye) - - # Check keywords and initialise options. - self.initialiseoptions() - - def goodbye(self, event = None): - self.destroy() - -class Demo: - def __init__(self, parent): - # Create button to launch the megawidget. - self.button = Tkinter.Button(parent, - command = self.showMessageInfo, - text = 'Show toplevel megawidget') - self.button.pack(padx = 8, pady = 8) - - self.count = 0 - self.parent = parent - - def showMessageInfo(self): - bitmaps = ('warning', 'hourglass', 'error', 'info', - 'gray25', 'gray50', 'question', 'questhead') - bitmap = bitmaps[self.count % len(bitmaps)] - - message = 'This is a demonstration of\na megawidget.\n' + \ - 'It contains a configurable\nmessage area and bitmap.\n' + \ - 'This instance is displaying\nthe "' + bitmap + '" bitmap.' - - # Make the toplevel window a child of this window, so that it - # is destroyed when the demo is destroyed. - MessageInfo(self.parent, message_text = message, icon_bitmap = bitmap) - - self.count = self.count + 1 - if self.count == 1: - self.button.configure(text = 'Show another\ntoplevel megawidget') - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/MultiLineLabel.py b/Pmw/Pmw_1_2/demos/MultiLineLabel.py deleted file mode 100644 index b08b4c15..00000000 --- a/Pmw/Pmw_1_2/demos/MultiLineLabel.py +++ /dev/null @@ -1,73 +0,0 @@ -title = 'Multi-line label demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import string -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - - frame = Tkinter.Frame(parent, background = '#eeeeee') - frame.pack(fill = 'both', expand = 1, padx = 5, pady = 5) - - stickys = ('n', 's', 'e', 'w', 'ns', 'ew', 'ne', 'nw', 'se', 'sw', - 'nsw', 'nse', 'new', 'sew', 'nsew',) - - widgets = [] - row = 0 - column = 0 - - # Choose one megawidget class to demonstrate: - cls = Pmw.EntryField - # cls = Pmw.Counter - # cls = Pmw.ComboBox - # cls = Pmw.LabeledWidget - # cls = Pmw.MessageBar - - for sticky in stickys: - dict = {} - dict['sticky'] = sticky - dict['labelpos'] = 'w' - dict['label_text'] = '1\n' + sticky + ':\n3' - if cls == Pmw.EntryField: - dict['value'] = sticky - dict['entry_width'] = 6 - if cls == Pmw.Counter or cls == Pmw.ComboBox: - dict['entryfield_value'] = sticky - dict['entry_width'] = 6 - widget = apply(cls, (frame,), dict) - if cls == Pmw.LabeledWidget: - f = Tkinter.Button(widget.interior(), text = sticky) - f.pack(fill = 'both', expand = 1) - if cls == Pmw.MessageBar: - widget.message('state', sticky) - widget.grid(column=column, row=row, sticky='ew', padx = 10, pady = 5) - frame.grid_columnconfigure(column, weight=1) - frame.grid_rowconfigure(row, weight=1) - - widgets.append(widget) - - if row < 4: - row = row + 1 - else: - row = 0 - column = column + 1 - - Pmw.alignlabels(widgets, sticky = 'e') - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/NestedDialogs.py b/Pmw/Pmw_1_2/demos/NestedDialogs.py deleted file mode 100644 index e8199a33..00000000 --- a/Pmw/Pmw_1_2/demos/NestedDialogs.py +++ /dev/null @@ -1,71 +0,0 @@ -title = 'Modal dialog nesting demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - # Create button to launch the dialog. - w = Tkinter.Button(parent, text = 'Show first dialog', - command = self.showFirstDialog) - w.pack(padx = 8, pady = 8) - - self.timerId = None - - self.dialog1 = Pmw.MessageDialog(parent, - message_text = 'This is the first modal dialog.\n' + - 'You can see how dialogs nest by\n' + - 'clicking on the "Next" button.', - title = 'Dialog 1', - buttons = ('Next', 'Cancel'), - defaultbutton = 'Next', - command = self.next_dialog) - self.dialog1.withdraw() - - self.dialog2 = Pmw.Dialog(self.dialog1.interior(), - title = 'Dialog 2', - buttons = ('Cancel',), - deactivatecommand = self.cancelTimer, - defaultbutton = 'Cancel') - self.dialog2.withdraw() - w = Tkinter.Label(self.dialog2.interior(), - text = 'This is the second modal dialog.\n' + - 'It will automatically disappear shortly') - w.pack(padx = 10, pady = 10) - - def showFirstDialog(self): - self.dialog1.activate() - - def cancelTimer(self): - if self.timerId is not None: - self.dialog2.after_cancel(self.timerId) - self.timerId = None - - def deactivateSecond(self): - self.timerId = None - self.dialog2.deactivate() - - def next_dialog(self, result): - if result != 'Next': - self.dialog1.deactivate() - return - - self.timerId = self.dialog2.after(3000, self.deactivateSecond) - self.dialog2.activate() - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/NoteBook.py b/Pmw/Pmw_1_2/demos/NoteBook.py deleted file mode 100644 index 20815a51..00000000 --- a/Pmw/Pmw_1_2/demos/NoteBook.py +++ /dev/null @@ -1,52 +0,0 @@ -title = 'Pmw.NoteBook demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - # Create and pack the NoteBook. - notebook = Pmw.NoteBook(parent) - notebook.pack(fill = 'both', expand = 1, padx = 10, pady = 10) - - # Add the "Appearance" page to the notebook. - page = notebook.add('Appearance') - notebook.tab('Appearance').focus_set() - - # Create the "Toolbar" contents of the page. - group = Pmw.Group(page, tag_text = 'Toolbar') - group.pack(fill = 'both', expand = 1, padx = 10, pady = 10) - b1 = Tkinter.Checkbutton(group.interior(), text = 'Show toolbar') - b1.grid(row = 0, column = 0) - b2 = Tkinter.Checkbutton(group.interior(), text = 'Toolbar tips') - b2.grid(row = 0, column = 1) - - # Create the "Startup" contents of the page. - group = Pmw.Group(page, tag_text = 'Startup') - group.pack(fill = 'both', expand = 1, padx = 10, pady = 10) - home = Pmw.EntryField(group.interior(), labelpos = 'w', - label_text = 'Home page location:') - home.pack(fill = 'x', padx = 20, pady = 10) - - # Add two more empty pages. - page = notebook.add('Helpers') - page = notebook.add('Images') - - notebook.setnaturalsize() - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - widget = Demo(root) - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack() - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/NoteBook_2.py b/Pmw/Pmw_1_2/demos/NoteBook_2.py deleted file mode 100644 index f42037a7..00000000 --- a/Pmw/Pmw_1_2/demos/NoteBook_2.py +++ /dev/null @@ -1,224 +0,0 @@ -title = 'Pmw.NoteBook demonstration (more complex)' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent, withTabs = 1): - - # Repeat random number sequence for each run. - self.rand = 12345 - - # Default demo is to display a tabbed notebook. - self.withTabs = withTabs - - # Create a frame to put everything in - self.mainframe = Tkinter.Frame(parent) - self.mainframe.pack(fill = 'both', expand = 1) - - # Find current default colors - button = Tkinter.Button() - defaultbg = button.cget('background') - defaultfg = button.cget('foreground') - button.destroy() - - # Create the list of colors to cycle through - self.colorList = [] - self.colorList.append((defaultbg, defaultfg)) - self.colorIndex = 0 - for color in Pmw.Color.spectrum(6, 1.5, 1.0, 1.0, 1): - bg = Pmw.Color.changebrightness(self.mainframe, color, 0.85) - self.colorList.append((bg, 'black')) - bg = Pmw.Color.changebrightness(self.mainframe, color, 0.55) - self.colorList.append((bg, 'white')) - - # Set the color to the current default - Pmw.Color.changecolor(self.mainframe, defaultbg, foreground = defaultfg) - defaultPalette = Pmw.Color.getdefaultpalette(self.mainframe) - Pmw.Color.setscheme(self.mainframe, defaultbg, foreground = defaultfg) - - # Create the notebook, but don't pack it yet. - if self.withTabs: - tabpos = 'n' - else: - tabpos = None - self.notebook = Pmw.NoteBook(self.mainframe, - tabpos = tabpos, - createcommand = PrintOne('Create'), - lowercommand = PrintOne('Lower'), - raisecommand = PrintOne('Raise'), - hull_width = 300, - hull_height = 200, - ) - - # Create a buttonbox to configure the notebook and pack it first. - buttonbox = Pmw.ButtonBox(self.mainframe) - buttonbox.pack(side = 'bottom', fill = 'x') - - # Add some buttons to the buttonbox to configure the notebook. - buttonbox.add('Insert\npage', command = self.insertpage) - buttonbox.add('Delete\npage', command = self.deletepage) - buttonbox.add('Add\nbutton', command = self.addbutton) - buttonbox.add('Change\ncolor', command = self.changecolor) - buttonbox.add('Natural\nsize', command = - self.notebook.setnaturalsize) - - if not self.withTabs: - # Create the selection widget to select the page in the notebook. - self.optionmenu = Pmw.OptionMenu(self.mainframe, - menubutton_width = 10, - command = self.notebook.selectpage - ) - self.optionmenu.pack(side = 'left', padx = 10) - - # Pack the notebook last so that the buttonbox does not disappear - # when the window is made smaller. - self.notebook.pack(fill = 'both', expand = 1, padx = 5, pady = 5) - - # Populate some pages of the notebook. - page = self.notebook.add('tmp') - self.notebook.delete('tmp') - page = self.notebook.add('Appearance') - if self.withTabs: - self.notebook.tab('Appearance').focus_set() - button = Tkinter.Button(page, - text = 'Welcome\nto\nthe\nAppearance\npage') - button.pack(expand = 1) - page = self.notebook.add('Fonts') - button = Tkinter.Button(page, - text = 'This is a very very very very wide Fonts page') - button.pack(expand = 1) - page = self.notebook.insert('Applications', before = 'Fonts') - button = Tkinter.Button(page, text = 'This is the Applications page') - button.pack(expand = 1) - - # Initialise the first page and the initial colour. - if not self.withTabs: - self.optionmenu.setitems(self.notebook.pagenames()) - apply(Pmw.Color.setscheme, (self.mainframe,), defaultPalette) - self.pageCounter = 0 - - def insertpage(self): - # Create a page at a random position - - defaultPalette = Pmw.Color.getdefaultpalette(self.mainframe) - bg, fg = self.colorList[self.colorIndex] - Pmw.Color.setscheme(self.mainframe, bg, foreground = fg) - - self.pageCounter = self.pageCounter + 1 - before = self.randomchoice(self.notebook.pagenames() + [Pmw.END]) - pageName = 'page%d' % self.pageCounter - if self.pageCounter % 5 == 0: - tab_text = pageName + '\nline two' - else: - tab_text = pageName - classes = (None, Tkinter.Button, Tkinter.Label, Tkinter.Checkbutton) - cls = self.randomchoice((None,) + classes) - if cls is None: - print 'Adding', pageName, 'as a frame with a button' - if self.withTabs: - page = self.notebook.insert(pageName, before, tab_text = tab_text) - else: - page = self.notebook.insert(pageName, before) - button = Tkinter.Button(page, - text = 'This is button %d' % self.pageCounter) - button.pack(expand = 1) - else: - print 'Adding', pageName, 'using', cls - if self.withTabs: - page = self.notebook.insert(pageName, before, - tab_text = tab_text, - page_pyclass = cls, - page_text = 'This is a page using\na %s' % str(cls) - ) - else: - page = self.notebook.insert(pageName, before, - page_pyclass = cls, - page_text = 'This is a page using\na %s' % str(cls) - ) - if not self.withTabs: - self.optionmenu.setitems( - self.notebook.pagenames(), self.notebook.getcurselection()) - - apply(Pmw.Color.setscheme, (self.mainframe,), defaultPalette) - - def addbutton(self): - # Add a button to a random page. - - defaultPalette = Pmw.Color.getdefaultpalette(self.mainframe) - bg, fg = self.colorList[self.colorIndex] - Pmw.Color.setscheme(self.mainframe, bg, foreground = fg) - - framePages = [] - for pageName in self.notebook.pagenames(): - page = self.notebook.page(pageName) - if page.__class__ == Tkinter.Frame: - framePages.append(pageName) - - if len(framePages) == 0: - self.notebook.bell() - return - - pageName = self.randomchoice(framePages) - print 'Adding extra button to', pageName - page = self.notebook.page(pageName) - button = Tkinter.Button(page, text = 'This is an extra button') - button.pack(expand = 1) - - apply(Pmw.Color.setscheme, (self.mainframe,), defaultPalette) - - def deletepage(self): - # Delete a random page - - pageNames = self.notebook.pagenames() - if len(pageNames) == 0: - self.notebook.bell() - return - - pageName = self.randomchoice(pageNames) - print 'Deleting', pageName - self.notebook.delete(pageName) - if not self.withTabs: - self.optionmenu.setitems( - self.notebook.pagenames(), self.notebook.getcurselection()) - - def changecolor(self): - self.colorIndex = self.colorIndex + 1 - if self.colorIndex == len(self.colorList): - self.colorIndex = 0 - - bg, fg = self.colorList[self.colorIndex] - print 'Changing color to', bg - Pmw.Color.changecolor(self.mainframe, bg, foreground = fg) - self.notebook.recolorborders() - - # Simple random number generator. - def randomchoice(self, selection): - num = len(selection) - self.rand = (self.rand * 125) % 2796203 - index = self.rand % num - return selection[index] - -class PrintOne: - def __init__(self, text): - self.text = text - - def __call__(self, text): - print self.text, text - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - widget = Demo(root) - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack() - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/NoteBook_3.py b/Pmw/Pmw_1_2/demos/NoteBook_3.py deleted file mode 100644 index 8106c5af..00000000 --- a/Pmw/Pmw_1_2/demos/NoteBook_3.py +++ /dev/null @@ -1,26 +0,0 @@ -title = 'Pmw.NoteBook demonstration (with no tabs)' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -# Reuse the NoteBook with tabs demo. -import NoteBook_2 - -class Demo(NoteBook_2.Demo): - def __init__(self, parent): - NoteBook_2.Demo.__init__(self, parent, withTabs = 0) - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - widget = Demo(root) - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack() - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/OptionMenu.py b/Pmw/Pmw_1_2/demos/OptionMenu.py deleted file mode 100644 index 11d7a88a..00000000 --- a/Pmw/Pmw_1_2/demos/OptionMenu.py +++ /dev/null @@ -1,66 +0,0 @@ -title = 'Pmw.OptionMenu demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - # Create and pack the OptionMenu megawidgets. - # The first one has a textvariable. - self.var = Tkinter.StringVar() - self.var.set('steamed') - self.method_menu = Pmw.OptionMenu(parent, - labelpos = 'w', - label_text = 'Choose method:', - menubutton_textvariable = self.var, - items = ['baked', 'steamed', 'stir fried', 'boiled', 'raw'], - menubutton_width = 10, - ) - self.method_menu.pack(anchor = 'w', padx = 10, pady = 10) - - self.vege_menu = Pmw.OptionMenu (parent, - labelpos = 'w', - label_text = 'Choose vegetable:', - items = ('broccoli', 'peas', 'carrots', 'pumpkin'), - menubutton_width = 10, - command = self._printOrder, - ) - self.vege_menu.pack(anchor = 'w', padx = 10, pady = 10) - - self.direction_menu = Pmw.OptionMenu (parent, - labelpos = 'w', - label_text = 'Menu direction:', - items = ('flush', 'above', 'below', 'left', 'right'), - menubutton_width = 10, - command = self._changeDirection, - ) - self.direction_menu.pack(anchor = 'w', padx = 10, pady = 10) - - menus = (self.method_menu, self.vege_menu, self.direction_menu) - Pmw.alignlabels(menus) - - def _printOrder(self, vege): - # Can use 'self.var.get()' instead of 'getcurselection()'. - print 'You have chosen %s %s.' % \ - (self.method_menu.getcurselection(), vege) - - def _changeDirection(self, direction): - for menu in (self.method_menu, self.vege_menu, self.direction_menu): - menu.configure(menubutton_direction = direction) - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/PanedWidget.py b/Pmw/Pmw_1_2/demos/PanedWidget.py deleted file mode 100644 index e8bdb22d..00000000 --- a/Pmw/Pmw_1_2/demos/PanedWidget.py +++ /dev/null @@ -1,103 +0,0 @@ -title = 'Pmw.PanedWidget demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - - # Create a main PanedWidget with a few panes. - self.pw = Pmw.PanedWidget(parent, - orient='vertical', - hull_borderwidth = 1, - hull_relief = 'sunken', - hull_width=300, - hull_height=400) - for self.numPanes in range(4): - if self.numPanes == 1: - name = 'Fixed size' - pane = self.pw.add(name, min = .1, max = .1) - else: - name = 'Pane ' + str(self.numPanes) - pane = self.pw.add(name, min = .1, size = .25) - label = Tkinter.Label(pane, text = name) - label.pack(side = 'left', expand = 1) - button = Tkinter.Button(pane, text = 'Delete', - command = lambda s=self, n=name: s.deletePane(n)) - button.pack(side = 'left', expand = 1) - # TODO: add buttons to invoke self.moveOneUp and self.moveOneUp. - - self.pw.pack(expand = 1, fill='both') - - buttonBox = Pmw.ButtonBox(parent) - buttonBox.pack(fill = 'x') - buttonBox.add('Add pane', command = self.addPane) - buttonBox.add('Move pane', command = self.move) - self.moveSrc = 0 - self.moveNewPos = 1 - self.moveBack = 0 - - def move(self): - numPanes = len(self.pw.panes()) - if numPanes == 0: - print 'No panes to move!' - return - - if self.moveSrc >= numPanes: - self.moveSrc = numPanes - 1 - if self.moveNewPos >= numPanes: - self.moveNewPos = numPanes - 1 - print 'Moving pane', self.moveSrc, 'to new position', self.moveNewPos - self.pw.move(self.moveSrc, self.moveNewPos) - - self.moveSrc, self.moveNewPos = self.moveNewPos, self.moveSrc - if self.moveBack: - if self.moveNewPos == numPanes - 1: - self.moveNewPos = 0 - if self.moveSrc == numPanes - 1: - self.moveSrc = 0 - else: - self.moveSrc = self.moveSrc + 1 - else: - self.moveNewPos = self.moveNewPos + 1 - self.moveBack = not self.moveBack - - def addPane(self): - self.numPanes = self.numPanes + 1 - name = 'Pane ' + str(self.numPanes) - print 'Adding', name - pane = self.pw.add(name, min = .1, size = .25) - label = Tkinter.Label(pane, text = name) - label.pack(side = 'left', expand = 1) - button = Tkinter.Button(pane, text = 'Delete', - command = lambda s=self, n=name: s.deletePane(n)) - button.pack(side = 'left', expand = 1) - self.pw.updatelayout() - - def deletePane(self, name): - print 'Deleting', name - self.pw.delete(name) - self.pw.updatelayout() - - def moveOneUp(self, name): - self.pw.move(name, name, -1) - - def moveOneDown(self, name): - self.pw.move(name, name, 1) - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/PanedWidget_2.py b/Pmw/Pmw_1_2/demos/PanedWidget_2.py deleted file mode 100644 index 334bced0..00000000 --- a/Pmw/Pmw_1_2/demos/PanedWidget_2.py +++ /dev/null @@ -1,65 +0,0 @@ -title = 'Pmw.PanedWidget demonstration (pane factory)' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - self.paneCount = 0 - - # Create a "pane factory". - label = Tkinter.Label(parent, - pady = 10, - text = 'Below is a simple "pane factory".\n' + - 'Drag the handle on the left\nto create new panes.') - label.pack() - self.factory = Pmw.PanedWidget(parent, - orient='horizontal', - command = self.resize, - hull_borderwidth = 1, - hull_relief = 'raised', - hull_width=300, hull_height=200 - ) - self.factory.add('starter', size = 0.0) - self.factory.add('main') - button = Tkinter.Button(self.factory.pane('main'), - text = 'Pane\n0') - button.pack(expand = 1) - self.factory.pack(expand = 1, fill = 'both') - - def resize(self, list): - # Remove any panes less than 2 pixel wide. - for i in range(len(list) - 1, 0, -1): - if list[i] < 2: - self.factory.delete(i) - - # If the user has dragged the left hand handle, create a new pane. - if list[0] > 1: - self.paneCount = self.paneCount + 1 - - # Add a button to the new pane. - name = self.factory.panes()[0] - text = 'Pane\n' + str(self.paneCount) - button = Tkinter.Button(self.factory.pane(name), text = text) - button.pack(expand = 1) - - # Create a new starter pane. - name = 'Pane ' + str(self.paneCount) - self.factory.insert(name, size=0.0) - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/PromptDialog.py b/Pmw/Pmw_1_2/demos/PromptDialog.py deleted file mode 100644 index 40f50f7d..00000000 --- a/Pmw/Pmw_1_2/demos/PromptDialog.py +++ /dev/null @@ -1,62 +0,0 @@ -title = 'Pmw.PromptDialog demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -# This may demonstrate a bug in Tk. Click on Cancel in the confirm -# dialog and then click on OK in the password dialog. Under Solaris -# 2.5 and python 1.5, the Cancel button in the confirm dialog is still -# displayed active, that is, it has a lighter background. - -class Demo: - def __init__(self, parent): - # Create the dialog to prompt for the password. - self.dialog = Pmw.PromptDialog(parent, - title = 'Password', - label_text = 'Password:', - entryfield_labelpos = 'n', - entry_show = '*', - defaultbutton = 0, - buttons = ('OK', 'Cancel'), - command = self.execute) - self.dialog.withdraw() - - # Create the confirmation dialog. - self.confirm = Pmw.MessageDialog( - title = 'Are you sure?', - message_text = 'Are you really sure?', - defaultbutton = 0, - buttons = ('OK', 'Cancel')) - self.confirm.withdraw() - - # Create button to launch the dialog. - w = Tkinter.Button(parent, text = 'Show prompt dialog', - command = self.dialog.activate) - w.pack(padx = 8, pady = 8) - - def execute(self, result): - if result is None or result == 'Cancel': - print 'Password prompt cancelled' - self.dialog.deactivate(result) - else: - result = self.confirm.activate() - if result == 'OK': - print 'Password entered ' + self.dialog.get() - self.dialog.deactivate() - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/RadioSelect.py b/Pmw/Pmw_1_2/demos/RadioSelect.py deleted file mode 100644 index fb549b72..00000000 --- a/Pmw/Pmw_1_2/demos/RadioSelect.py +++ /dev/null @@ -1,116 +0,0 @@ -title = 'Pmw.RadioSelect demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - # Create and pack a horizontal RadioSelect widget. - horiz = Pmw.RadioSelect(parent, - labelpos = 'w', - command = self.callback, - label_text = 'Horizontal', - frame_borderwidth = 2, - frame_relief = 'ridge' - ) - horiz.pack(fill = 'x', padx = 10, pady = 10) - - # Add some buttons to the horizontal RadioSelect. - for text in ('Fruit', 'Vegetables', 'Cereals', 'Legumes'): - horiz.add(text) - horiz.invoke('Cereals') - - # Create and pack a multiple selection RadioSelect widget. - self.multiple = Pmw.RadioSelect(parent, - labelpos = 'w', - command = self.multcallback, - label_text = 'Multiple\nselection', - frame_borderwidth = 2, - frame_relief = 'ridge', - selectmode = 'multiple', - ) - self.multiple.pack(fill = 'x', padx = 10) - - # Add some buttons to the multiple selection RadioSelect. - for text in ('Apricots', 'Eggplant', 'Rice', 'Lentils'): - self.multiple.add(text) - self.multiple.invoke('Rice') - - # Create and pack a vertical RadioSelect widget, with checkbuttons. - self.checkbuttons = Pmw.RadioSelect(parent, - buttontype = 'checkbutton', - orient = 'vertical', - labelpos = 'w', - command = self.checkbuttoncallback, - label_text = 'Vertical,\nusing\ncheckbuttons', - hull_borderwidth = 2, - hull_relief = 'ridge', - ) - self.checkbuttons.pack(side = 'left', expand = 1, padx = 10, pady = 10) - - # Add some buttons to the checkbutton RadioSelect. - for text in ('Male', 'Female'): - self.checkbuttons.add(text) - self.checkbuttons.invoke('Male') - self.checkbuttons.invoke('Female') - - # Create and pack a RadioSelect widget, with radiobuttons. - radiobuttons = Pmw.RadioSelect(parent, - buttontype = 'radiobutton', - orient = 'vertical', - labelpos = 'w', - command = self.callback, - label_text = 'Vertical,\nusing\nradiobuttons', - hull_borderwidth = 2, - hull_relief = 'ridge', - ) - radiobuttons.pack(side = 'left', expand = 1, padx = 10, pady = 10) - - # Add some buttons to the radiobutton RadioSelect. - for text in ('Male', 'Female', 'Both', 'Neither'): - radiobuttons.add(text) - radiobuttons.invoke('Both') - - def callback(self, tag): - # This is called whenever the user clicks on a button - # in a single select RadioSelect widget. - print 'Button', tag, 'was pressed.' - - def multcallback(self, tag, state): - # This is called whenever the user clicks on a button - # in the multiple select RadioSelect widget. - if state: - action = 'pressed.' - else: - action = 'released.' - - print 'Button', tag, 'was', action, \ - 'Selection:', self.multiple.getcurselection() - - def checkbuttoncallback(self, tag, state): - # This is called whenever the user clicks on a button - # in the checkbutton RadioSelect widget. - if state: - action = 'pressed.' - else: - action = 'released.' - - print 'Button', tag, 'was', action, \ - 'Selection:', self.checkbuttons.getcurselection() - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/Resources.py b/Pmw/Pmw_1_2/demos/Resources.py deleted file mode 100644 index 2168b4ac..00000000 --- a/Pmw/Pmw_1_2/demos/Resources.py +++ /dev/null @@ -1,74 +0,0 @@ -title = 'Using Tk option database to configure Tk widgets' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import string -import Tkinter -import Pmw - -info = """ - The Tk widgets contained in this - simple megawidget have been - configured using the Tk option - database. - *DemoClass*Listbox.cursor is 'heart' - *DemoClass*Entry.cursor is 'hand1' - *DemoClass*background is 'pink' - *DemoClass*highlightBackground is 'green' - *DemoClass*foreground is 'blue' -""" - -class DemoClass(Pmw.MegaWidget): - - # Demo Pmw megawidget. - - def __init__(self, parent = None, **kw): - - # Define the megawidget options. - optiondefs = () - self.defineoptions(kw, optiondefs) - - # Initialise the base class (after defining the options). - Pmw.MegaWidget.__init__(self, parent) - - interior = self.interior() - listbox = Tkinter.Listbox(interior, height = 12, width = 40) - listbox.pack(fill='both', expand='yes') - for line in string.split(info, '\n'): - listbox.insert('end', line) - - entry = Tkinter.Entry(interior) - entry.pack(fill='y') - entry.insert(0, 'Hello, World!') - - # Check keywords and initialise options. - self.initialiseoptions() - -class Demo: - def __init__(self, parent): - - # Test Tk option database settings. - parent.option_add('*DemoClass*Listbox.cursor', 'heart') - parent.option_add('*DemoClass*Entry.cursor', 'hand1') - parent.option_add('*DemoClass*background', 'pink') - parent.option_add('*DemoClass*highlightBackground', 'green') - parent.option_add('*DemoClass*foreground', 'blue') - - # Create and pack the megawidget. - demo = DemoClass(parent) - demo.pack(fill = 'both', expand = 1) - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/Resources_Pmw.py b/Pmw/Pmw_1_2/demos/Resources_Pmw.py deleted file mode 100644 index a1f2f992..00000000 --- a/Pmw/Pmw_1_2/demos/Resources_Pmw.py +++ /dev/null @@ -1,110 +0,0 @@ -title = 'Using Tk option database to configure Pmw megawidgets' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - self.parent = parent - - header = Tkinter.Label(parent, text = 'Select some Tk option ' + - 'database values from\nthe lists, then click ' + - '\'Create dialog\' to create\na MessageDialog with ' + - 'these values as defaults.') - header.pack(padx = 10, pady = 10) - - # Create and pack the ComboBoxes to select options. - buttons = ( - "('OK',)", - "('Read', 'Write')", - "('OK', 'Cancel')", - "('OK', 'Apply', 'Cancel', 'Help')", - ) - - if Tkinter.TkVersion >= 8.4: - disabledState = 'readonly' - else: - disabledState = 'disabled' - - self._buttons = Pmw.ComboBox(parent, label_text = 'buttons:', - labelpos = 'w', - entry_state = disabledState, - scrolledlist_items = buttons) - self._buttons.pack(fill = 'x', expand = 1, padx = 8, pady = 8) - self._buttons.selectitem(3) - - buttonboxpos = ('n', 's', 'e', 'w',) - self._buttonboxpos = Pmw.ComboBox(parent, label_text = 'buttonboxpos:', - labelpos = 'w', - entry_state = disabledState, - scrolledlist_items = buttonboxpos) - self._buttonboxpos.pack(fill = 'x', expand = 1, padx = 8, pady = 8) - self._buttonboxpos.selectitem(2) - - pad = ('0', '8', '20', '50',) - self._pad = Pmw.ComboBox(parent, label_text = 'padx, pady:', - labelpos = 'w', - entry_state = disabledState, - scrolledlist_items = pad) - self._pad.pack(fill = 'x', expand = 1, padx = 8, pady = 8) - self._pad.selectitem(1) - - Pmw.alignlabels((self._buttons, self._buttonboxpos, self._pad)) - - # Create button to launch the dialog. - w = Tkinter.Button(parent, text = 'Create dialog', - command = self._createDialog) - w.pack(padx = 8, pady = 8) - - self.dialog = None - - def _createDialog(self): - - # Set the option database. - buttons = self._buttons.get() - buttonboxpos = self._buttonboxpos.get() - pad = self._pad.get() - self.parent.option_add('*MessageDialog.buttons', buttons) - self.parent.option_add('*MessageDialog.buttonboxpos', buttonboxpos) - self.parent.option_add('*ButtonBox.padx', pad) - self.parent.option_add('*ButtonBox.pady', pad) - - # Create the dialog. - if self.dialog is not None: - self.dialog.destroy() - - text = ('This dialog was created by setting the Tk ' + - 'option database:\n\n *MessageDialog.buttons: ' + buttons + - '\n *MessageDialog.buttonboxpos: ' + buttonboxpos + - '\n *ButtonBox.padx: ' + pad + - '\n *ButtonBox.pady: ' + pad) - self.dialog = Pmw.MessageDialog(self.parent, - defaultbutton = 0, - title = 'Pmw option database demonstration', - message_justify = 'left', - message_text = text) - self.dialog.iconname('Test dialog') - - # Return the defaults to normal, otherwise all other demos - # will be affected. - self.parent.option_add('*MessageDialog.buttons', "('OK',)") - self.parent.option_add('*MessageDialog.buttonboxpos', 's') - self.parent.option_add('*ButtonBox.padx', 8) - self.parent.option_add('*ButtonBox.pady', 8) - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root, useTkOptionDb = 1) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/ScrolledCanvas.py b/Pmw/Pmw_1_2/demos/ScrolledCanvas.py deleted file mode 100644 index 28933ec5..00000000 --- a/Pmw/Pmw_1_2/demos/ScrolledCanvas.py +++ /dev/null @@ -1,124 +0,0 @@ -title = 'Pmw.ScrolledCanvas demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - # Create the ScrolledCanvas. - self.sc = Pmw.ScrolledCanvas(parent, - borderframe = 1, - labelpos = 'n', - label_text = 'ScrolledCanvas', - usehullsize = 1, - hull_width = 400, - hull_height = 300, - ) - - # Create a group widget to contain the scrollmode options. - w = Pmw.Group(parent, tag_text='Scroll mode') - w.pack(side = 'bottom', padx = 5, pady = 5) - - hmode = Pmw.OptionMenu(w.interior(), - labelpos = 'w', - label_text = 'Horizontal:', - items = ['none', 'static', 'dynamic'], - command = self.sethscrollmode, - menubutton_width = 8, - ) - hmode.pack(side = 'left', padx = 5, pady = 5) - hmode.invoke('dynamic') - - vmode = Pmw.OptionMenu(w.interior(), - labelpos = 'w', - label_text = 'Vertical:', - items = ['none', 'static', 'dynamic'], - command = self.setvscrollmode, - menubutton_width = 8, - ) - vmode.pack(side = 'left', padx = 5, pady = 5) - vmode.invoke('dynamic') - - buttonBox = Pmw.ButtonBox(parent) - buttonBox.pack(side = 'bottom') - buttonBox.add('yview', text = 'Show\nyview', command = self.showYView) - buttonBox.add('scroll', text = 'Page\ndown', command = self.pageDown) - buttonBox.add('center', text = 'Center', command = self.centerPage) - - # Pack this last so that the buttons do not get shrunk when - # the window is resized. - self.sc.pack(padx = 5, pady = 5, fill = 'both', expand = 1) - - self.sc.component('canvas').bind('<1>', self.addcircle) - - testEntry = Tkinter.Entry(parent) - self.sc.create_line(20, 20, 100, 100) - self.sc.create_oval(100, 100, 200, 200, fill = 'green') - self.sc.create_text(100, 20, anchor = 'nw', - text = 'Click in the canvas\nto draw ovals', - font = testEntry.cget('font')) - button = Tkinter.Button(self.sc.interior(), - text = 'Hello,\nWorld!\nThis\nis\na\nbutton.') - self.sc.create_window(200, 200, - anchor='nw', - window = button) - - # Set the scroll region of the canvas to include all the items - # just created. - self.sc.resizescrollregion() - - self.colours = ('red', 'green', 'blue', 'yellow', 'cyan', 'magenta', - 'black', 'white') - self.oval_count = 0 - self.rand = 12345 - - def sethscrollmode(self, tag): - self.sc.configure(hscrollmode = tag) - - def setvscrollmode(self, tag): - self.sc.configure(vscrollmode = tag) - - def addcircle(self, event): - x = self.sc.canvasx(event.x) - y = self.sc.canvasy(event.y) - width = 10 + self.random() % 100 - height = 10 + self.random() % 100 - self.sc.create_oval( - x - width, y - height, x + width, y + height, - fill = self.colours[self.oval_count]) - self.oval_count = (self.oval_count + 1) % len(self.colours) - self.sc.resizescrollregion() - - # Simple random number generator. - def random(self): - self.rand = (self.rand * 125) % 2796203 - return self.rand - - def showYView(self): - print self.sc.yview() - - def pageDown(self): - self.sc.yview('scroll', 1, 'page') - - def centerPage(self): - top, bottom = self.sc.yview() - size = bottom - top - middle = 0.5 - size / 2 - self.sc.yview('moveto', middle) - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/ScrolledField.py b/Pmw/Pmw_1_2/demos/ScrolledField.py deleted file mode 100644 index b3a268df..00000000 --- a/Pmw/Pmw_1_2/demos/ScrolledField.py +++ /dev/null @@ -1,51 +0,0 @@ -title = 'Pmw.ScrolledField demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - # Create and pack the ScrolledField. - self._field = Pmw.ScrolledField(parent, entry_width = 30, - entry_relief='groove', labelpos = 'n', - label_text = 'Scroll the field using the\nmiddle mouse button') - self._field.pack(fill = 'x', expand = 1, padx = 10, pady = 10) - - # Create and pack a button to change the ScrolledField. - self._button = Tkinter.Button(parent, text = 'Change field', - command = self.execute) - self._button.pack(padx = 10, pady = 10) - - self._index = 0 - self.execute() - - def execute(self): - self._field.configure(text = lines[self._index % len(lines)]) - self._index = self._index + 1 - -lines = ( - 'Alice was beginning to get very tired of sitting by her sister', - 'on the bank, and of having nothing to do: once or twice she had', - 'peeped into the book her sister was reading, but it had no', - 'pictures or conversations in it, "and what is the use of a book,"', - 'thought Alice "without pictures or conversation?"', - 'Alice\'s Adventures in Wonderland', - 'Lewis Carroll', -) - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/ScrolledFrame.py b/Pmw/Pmw_1_2/demos/ScrolledFrame.py deleted file mode 100644 index 06880df1..00000000 --- a/Pmw/Pmw_1_2/demos/ScrolledFrame.py +++ /dev/null @@ -1,157 +0,0 @@ -title = 'Pmw.ScrolledFrame demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - # Create the ScrolledFrame. - self.sf = Pmw.ScrolledFrame(parent, - labelpos = 'n', label_text = 'ScrolledFrame', - usehullsize = 1, - hull_width = 400, - hull_height = 220, - ) - - # Create a group widget to contain the flex options. - w = Pmw.Group(parent, tag_text='Flex') - w.pack(side = 'bottom', padx = 5, pady = 3) - - hflex = Pmw.OptionMenu(w.interior(), - labelpos = 'w', - label_text = 'Horizontal:', - items = ['fixed', 'expand', 'shrink', 'elastic'], - command = self.sethflex, - menubutton_width = 8, - ) - hflex.pack(side = 'left', padx = 5, pady = 3) - hflex.invoke('fixed') - - vflex = Pmw.OptionMenu(w.interior(), - labelpos = 'w', - label_text = 'Vertical:', - items = ['fixed', 'expand', 'shrink', 'elastic'], - command = self.setvflex, - menubutton_width = 8, - ) - vflex.pack(side = 'left', padx = 5, pady = 3) - vflex.invoke('fixed') - - # Create a group widget to contain the scrollmode options. - w = Pmw.Group(parent, tag_text='Scroll mode') - w.pack(side = 'bottom', padx = 5, pady = 0) - - hmode = Pmw.OptionMenu(w.interior(), - labelpos = 'w', - label_text = 'Horizontal:', - items = ['none', 'static', 'dynamic'], - command = self.sethscrollmode, - menubutton_width = 8, - ) - hmode.pack(side = 'left', padx = 5, pady = 3) - hmode.invoke('dynamic') - - vmode = Pmw.OptionMenu(w.interior(), - labelpos = 'w', - label_text = 'Vertical:', - items = ['none', 'static', 'dynamic'], - command = self.setvscrollmode, - menubutton_width = 8, - ) - vmode.pack(side = 'left', padx = 5, pady = 3) - vmode.invoke('dynamic') - - self.radio = Pmw.RadioSelect(parent, selectmode = 'multiple', - command = self.radioSelected) - self.radio.add('center', text = 'Keep centered vertically') - self.radio.pack(side = 'bottom') - - buttonBox = Pmw.ButtonBox(parent) - buttonBox.pack(side = 'bottom') - buttonBox.add('add', text = 'Add a button', command = self.addButton) - buttonBox.add('yview', text = 'Show yview', command = self.showYView) - buttonBox.add('scroll', text = 'Page down', command = self.pageDown) - - # Pack this last so that the buttons do not get shrunk when - # the window is resized. - self.sf.pack(padx = 5, pady = 3, fill = 'both', expand = 1) - - self.frame = self.sf.interior() - - self.row = 0 - self.col = 0 - - for count in range(15): - self.addButton() - - def sethscrollmode(self, tag): - self.sf.configure(hscrollmode = tag) - - def setvscrollmode(self, tag): - self.sf.configure(vscrollmode = tag) - - def sethflex(self, tag): - self.sf.configure(horizflex = tag) - - def setvflex(self, tag): - self.sf.configure(vertflex = tag) - - def addButton(self): - button = Tkinter.Button(self.frame, - text = '(%d,%d)' % (self.col, self.row)) - button.grid(row = self.row, column = self.col, sticky = 'nsew') - - self.frame.grid_rowconfigure(self.row, weight = 1) - self.frame.grid_columnconfigure(self.col, weight = 1) - if self.sf.cget('horizflex') == 'expand' or \ - self.sf.cget('vertflex') == 'expand': - self.sf.reposition() - - if 'center' in self.radio.getcurselection(): - self.sf.update_idletasks() - self.centerPage() - - if self.col == self.row: - self.col = 0 - self.row = self.row + 1 - else: - self.col = self.col + 1 - - def showYView(self): - print self.sf.yview() - - def pageDown(self): - self.sf.yview('scroll', 1, 'page') - - def radioSelected(self, name, state): - if state: - self.centerPage() - - def centerPage(self): - # Example of how to use the yview() method of Pmw.ScrolledFrame. - top, bottom = self.sf.yview() - size = bottom - top - middle = 0.5 - size / 2 - self.sf.yview('moveto', middle) - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - import os - if os.name == 'nt': - size = 16 - else: - size = 12 - root = Tkinter.Tk() - Pmw.initialise(root, size = size, fontScheme = 'pmw2') - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/ScrolledListBox.py b/Pmw/Pmw_1_2/demos/ScrolledListBox.py deleted file mode 100644 index f2f7d9d6..00000000 --- a/Pmw/Pmw_1_2/demos/ScrolledListBox.py +++ /dev/null @@ -1,118 +0,0 @@ -title = 'Pmw.ScrolledListBox demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - # Create the ScrolledListBox. - self.box = Pmw.ScrolledListBox(parent, - items=('Sydney', 'Melbourne', 'Brisbane'), - labelpos='nw', - label_text='Cities', - listbox_height = 6, - selectioncommand=self.selectionCommand, - dblclickcommand=self.defCmd, - usehullsize = 1, - hull_width = 200, - hull_height = 200, - ) - - # Create a group widget to contain the scrollmode options. - w = Pmw.Group(parent, tag_text='Scroll mode') - w.pack(side = 'bottom', padx = 5, pady = 5) - - hmode = Pmw.OptionMenu(w.interior(), - labelpos = 'w', - label_text = 'Horizontal:', - items = ['none', 'static', 'dynamic'], - command = self.sethscrollmode, - menubutton_width = 8, - ) - hmode.pack(side = 'top', padx = 5, pady = 5) - hmode.invoke('dynamic') - - vmode = Pmw.OptionMenu(w.interior(), - labelpos = 'w', - label_text = 'Vertical:', - items = ['none', 'static', 'dynamic'], - command = self.setvscrollmode, - menubutton_width = 8, - ) - vmode.pack(side = 'top', padx = 5, pady = 5) - vmode.invoke('dynamic') - - buttonBox = Pmw.ButtonBox(parent) - buttonBox.pack(side = 'bottom') - buttonBox.add('yview', text = 'Show\nyview', command = self.showYView) - buttonBox.add('scroll', text = 'Page\ndown', command = self.pageDown) - buttonBox.add('center', text = 'Center', command = self.centerPage) - - # Pack this last so that the buttons do not get shrunk when - # the window is resized. - self.box.pack(fill = 'both', expand = 1, padx = 5, pady = 5) - - # Do this after packing the scrolled list box, so that the - # window does not resize as soon as it appears (because - # alignlabels has to do an update_idletasks). - Pmw.alignlabels((hmode, vmode)) - - # Add some more entries to the listbox. - items = ('Andamooka', 'Coober Pedy', 'Innamincka', 'Oodnadatta') - self.box.setlist(items) - self.box.insert(2, 'Wagga Wagga', 'Perth', 'London') - self.box.insert('end', 'Darwin', 'Auckland', 'New York') - index = list(self.box.get(0, 'end')).index('London') - self.box.delete(index) - self.box.delete(7, 8) - self.box.insert('end', 'Bulli', 'Alice Springs', 'Woy Woy') - self.box.insert('end', 'Wallumburrawang', 'Willandra Billabong') - - def sethscrollmode(self, tag): - self.box.configure(hscrollmode = tag) - - def setvscrollmode(self, tag): - self.box.configure(vscrollmode = tag) - - def selectionCommand(self): - sels = self.box.getcurselection() - if len(sels) == 0: - print 'No selection' - else: - print 'Selection:', sels[0] - - def defCmd(self): - sels = self.box.getcurselection() - if len(sels) == 0: - print 'No selection for double click' - else: - print 'Double click:', sels[0] - - def showYView(self): - print self.box.yview() - - def pageDown(self): - self.box.yview('scroll', 1, 'page') - - def centerPage(self): - top, bottom = self.box.yview() - size = bottom - top - middle = 0.5 - size / 2 - self.box.yview('moveto', middle) - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/ScrolledText.py b/Pmw/Pmw_1_2/demos/ScrolledText.py deleted file mode 100644 index aae02ea2..00000000 --- a/Pmw/Pmw_1_2/demos/ScrolledText.py +++ /dev/null @@ -1,99 +0,0 @@ -title = 'Pmw.ScrolledText demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import os -import math -import string -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - - # Create the ScrolledText with headers. - fixedFont = Pmw.logicalfont('Fixed') - self.st = Pmw.ScrolledText(parent, - # borderframe = 1, - labelpos = 'n', - label_text='ScrolledText with headers', - columnheader = 1, - rowheader = 1, - rowcolumnheader = 1, - usehullsize = 1, - hull_width = 400, - hull_height = 300, - text_wrap='none', - text_font = fixedFont, - Header_font = fixedFont, - Header_foreground = 'blue', - rowheader_width = 3, - rowcolumnheader_width = 3, - text_padx = 4, - text_pady = 4, - Header_padx = 4, - rowheader_pady = 4, - ) - - self.st.pack(padx = 5, pady = 5, fill = 'both', expand = 1) - - funcs = 'atan cos cosh exp log log10 sin sinh sqrt tan tanh' - funcs = string.split(funcs) - - # Create the header for the row headers - self.st.component('rowcolumnheader').insert('end', 'x') - - # Create the column headers - headerLine = '' - for column in range(len(funcs)): - headerLine = headerLine + ('%-7s ' % (funcs[column],)) - headerLine = headerLine[:-3] - self.st.component('columnheader').insert('0.0', headerLine) - - self.st.tag_configure('yellow', background = 'yellow') - - # Create the data rows and the row headers - numRows = 50 - tagList = [] - for row in range(1, numRows): - dataLine = '' - x = row / 5.0 - for column in range(len(funcs)): - value = eval('math.' + funcs[column] + '(' + str(x) + ')') - data = str(value)[:7] - if value < 0: - tag1 = '%d.%d' % (row, len(dataLine)) - tag2 = '%d.%d' % (row, len(dataLine) + len(data)) - tagList.append(tag1) - tagList.append(tag2) - data = '%-7s' % (data,) - dataLine = dataLine + data + ' ' - dataLine = dataLine[:-3] - header = '%.1f' % (x,) - if row < numRows - 1: - dataLine = dataLine + '\n' - header = header + '\n' - self.st.insert('end', dataLine) - self.st.component('rowheader').insert('end', header) - apply(self.st.tag_add, ('yellow',) + tuple(tagList)) - - # Prevent users' modifying text and headers - self.st.configure( - text_state = 'disabled', - Header_state = 'disabled', - ) - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/ScrolledText_2.py b/Pmw/Pmw_1_2/demos/ScrolledText_2.py deleted file mode 100644 index cffb733a..00000000 --- a/Pmw/Pmw_1_2/demos/ScrolledText_2.py +++ /dev/null @@ -1,99 +0,0 @@ -title = 'Pmw.ScrolledText demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import os -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - # Create the ScrolledText. - self.st = Pmw.ScrolledText(parent, - borderframe = 1, - labelpos = 'n', - label_text='ScrolledText.py', - usehullsize = 1, - hull_width = 400, - hull_height = 300, - text_padx = 10, - text_pady = 10, - text_wrap='none' - ) - - # Create a group widget to contain the scrollmode options. - w = Pmw.Group(parent, tag_text='Scroll mode') - w.pack(side = 'bottom', padx = 5, pady = 5) - - hmode = Pmw.OptionMenu(w.interior(), - labelpos = 'w', - label_text = 'Horizontal:', - items = ['none', 'static', 'dynamic'], - command = self.sethscrollmode, - menubutton_width = 8, - ) - hmode.pack(side = 'left', padx = 5, pady = 5) - hmode.invoke('dynamic') - - vmode = Pmw.OptionMenu(w.interior(), - labelpos = 'w', - label_text = 'Vertical:', - items = ['none', 'static', 'dynamic'], - command = self.setvscrollmode, - menubutton_width = 8, - ) - vmode.pack(side = 'left', padx = 5, pady = 5) - vmode.invoke('dynamic') - - buttonBox = Pmw.ButtonBox(parent) - buttonBox.pack(side = 'bottom') - buttonBox.add('yview', text = 'Show\nyview', command = self.showYView) - buttonBox.add('scroll', text = 'Page\ndown', command = self.pageDown) - buttonBox.add('center', text = 'Center', command = self.centerPage) - - # Pack this last so that the buttons do not get shrunk when - # the window is resized. - self.st.pack(padx = 5, pady = 5, fill = 'both', expand = 1) - - # Read this file into the text widget. - head, tail = os.path.split(sys.argv[0]) - self.st.importfile(os.path.join(head,'ScrolledText.py')) - - self.st.insert('end', '\nThis demonstrates how to\n' + - 'add a window to a text widget: ') - counter = Pmw.Counter(self.st.component('text'), - entryfield_value = 9999) - self.st.window_create('end', window = counter) - - def sethscrollmode(self, tag): - self.st.configure(hscrollmode = tag) - - def setvscrollmode(self, tag): - self.st.configure(vscrollmode = tag) - - def showYView(self): - print self.st.yview() - - def pageDown(self): - self.st.yview('scroll', 1, 'page') - - def centerPage(self): - top, bottom = self.st.yview() - size = bottom - top - middle = 0.5 - size / 2 - self.st.yview('moveto', middle) - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/SelectionDialog.py b/Pmw/Pmw_1_2/demos/SelectionDialog.py deleted file mode 100644 index 12fea94d..00000000 --- a/Pmw/Pmw_1_2/demos/SelectionDialog.py +++ /dev/null @@ -1,47 +0,0 @@ -title = 'Pmw.SelectionDialog demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - # Create the dialog. - self.dialog = Pmw.SelectionDialog(parent, - title = 'My SelectionDialog', - buttons = ('OK', 'Cancel'), - defaultbutton = 'OK', - scrolledlist_labelpos = 'n', - label_text = 'What do you think of Pmw?', - scrolledlist_items = ('Cool man', 'Cool', 'Good', 'Bad', 'Gross'), - command = self.execute) - self.dialog.withdraw() - - # Create button to launch the dialog. - w = Tkinter.Button(parent, text = 'Show selection dialog', - command = self.dialog.activate) - w.pack(padx = 8, pady = 8) - - def execute(self, result): - sels = self.dialog.getcurselection() - if len(sels) == 0: - print 'You clicked on', result, '(no selection)' - else: - print 'You clicked on', result, sels[0] - self.dialog.deactivate(result) - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/ShowBusy.py b/Pmw/Pmw_1_2/demos/ShowBusy.py deleted file mode 100644 index 831b7a56..00000000 --- a/Pmw/Pmw_1_2/demos/ShowBusy.py +++ /dev/null @@ -1,48 +0,0 @@ -title = 'Blt busy cursor demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - self.parent = parent - - if Pmw.Blt.havebltbusy(parent): - text = 'Click here to show the\nbusy cursor for one second.' - else: - text = 'Sorry\n' \ - 'Either the BLT package has not\n' \ - 'been installed on this system or\n' \ - 'it does not support the busy command.\n' \ - 'Clicking on this button will pause\n' \ - 'for one second but will not display\n' \ - 'the busy cursor.' - - button = Tkinter.Button(parent, - text = text, - command = Pmw.busycallback(self.sleep, parent.update)) - button.pack(padx = 10, pady = 10) - - entry = Tkinter.Entry(parent, width = 30) - entry.insert('end', 'Try to enter some text while busy.') - entry.pack(padx = 10, pady = 10) - - def sleep(self): - self.parent.after(1000) - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/SpecialCounter.py b/Pmw/Pmw_1_2/demos/SpecialCounter.py deleted file mode 100644 index a76645a1..00000000 --- a/Pmw/Pmw_1_2/demos/SpecialCounter.py +++ /dev/null @@ -1,68 +0,0 @@ -title = 'Subclassing Pmw.Counter' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import string -import time -import types -import Tkinter -import Pmw - -class LabeledDateCounter(Pmw.Counter): - - def __init__(self, parent=None , **kw): - - # Need to use long ints here because on the Macintosh the maximum size - # of an integer is smaller than the value returned by time.time(). - now = (long(time.time()) / 300) * 300 - text = time.strftime('%y/%m/%d', time.localtime(now)) - - kw['datatype'] = 'date' - kw['entryfield_validate'] = 'date' - kw['entryfield_value'] = text - kw['labelpos'] = 'w' - - apply(Pmw.Counter.__init__, (self, parent), kw) - -class LabeledRealCounter(Pmw.Counter): - - def __init__(self, parent=None , **kw): - - # Define the validate option dictionary. - validate = {'validator' : 'real', 'min' : 0.0, 'max' : 100.0} - - kw['datatype'] = 'real' - kw['entryfield_validate'] = validate - kw['entryfield_value'] = 50.0 - kw['labelpos'] = 'w' - - apply(Pmw.Counter.__init__, (self, parent), kw) - -class Demo: - def __init__(self, parent): - # Create and pack some LabeledDateCounters and LabeledRealCounter. - self._date1 = LabeledDateCounter(parent, label_text = 'Date:') - self._date2 = LabeledDateCounter(parent, label_text = 'Another Date:') - self._real1 = LabeledRealCounter(parent, label_text = 'Real:') - self._real2 = LabeledRealCounter(parent, label_text = 'Another Real:') - - counters = (self._date1, self._date2, self._real1, self._real2) - - for counter in counters: - counter.pack(fill='x', expand=1, padx=10, pady=5) - Pmw.alignlabels(counters) - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/SpecialEntry.py b/Pmw/Pmw_1_2/demos/SpecialEntry.py deleted file mode 100644 index 270780b5..00000000 --- a/Pmw/Pmw_1_2/demos/SpecialEntry.py +++ /dev/null @@ -1,170 +0,0 @@ -title = 'Subclassing Pmw.EntryField' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import string -import time -import types -import Tkinter -import Pmw - -class SpecialEntry(Pmw.EntryField): - - def __init__(self, parent=None , **kw): - - kw['extravalidators'] = _myValidators - apply(Pmw.EntryField.__init__, (self, parent), kw) - self._converter = None - - def setentry(self, text): - # Override Pmw.EntryField.setentry to pass string through - # the appropriate converter. - - val = self['validate'] - if type(val) == types.DictionaryType: - val = val['validator'] - if _converters.has_key(val): - text = _converters[val](text, output = 0) - Pmw.EntryField.setentry(self, text) - - def getentry(self): - text = self.get() - val = self['validate'] - if type(val) == types.DictionaryType: - val = val['validator'] - if _converters.has_key(val): - return _converters[val](text, output = 1) - else: - return text - -def _date(text): - return Pmw.datevalidator(text, 'dmy', '.') - -def _real(text): - return Pmw.realvalidator(text, ',') - -def _dateconv(text, output = 0): - # On output, convert from dd.mm.yy to mm-dd-yy. On input, convert - # mm-dd-yy to dd.mm.yy and also from +NN+ or -NN- to date NN days - # before or after today. - - if len(text) == 0: - return '' - if output: - try: - d = string.split(text, '.') - return d[1] + '-' + d[0] + '-' + d[2] - except: - return text - else: - if text[-1] == '+' or text[-1] == '-': - text = text[:-1] - if text[0] == '+' or text[0] == '-': - secondsAhead = string.atoi(text) * 3600 * 24 - return time.strftime('%d.%m.%Y', - time.localtime(time.time() + secondsAhead)) - try: - d = string.split(text,'-') - return d[1] + '.' + d[0] + '.' + d[2] - except: - return text - -def _realconv(text, output = 0): - # Convert between DD.DD and DD,DD. - - if output: - index = string.find(text, ',') - if index >= 0: - return text[:index] + '.' + text[index + 1:] - else: - return text - else: - index = string.find(text, '.') - if index >= 0: - return text[:index] + ',' + text[index + 1:] - else: - return text - - -_converters = { - 'real' : _realconv, - 'float8' : _realconv, - 'date' : _dateconv -} - -_myValidators = { - 'date' : (_date, lambda s: Pmw.datestringtojdn(s, 'dmy', '.')), - 'real' : (_real, lambda s: string.atof(_realconv(s, 1))), - 'int4' : ('numeric', 'numeric'), - 'oid' : ('int4', 'int4'), - 'float8' : ('real', 'real'), - 'varchar' : ('alphanumeric', 'alphanumeric'), - 'text' : ('alphanumeric', 'alphanumeric'), -} - -class Demo: - def __init__(self, parent): - # Create and pack the SpecialEntry megawidgets. - self._any = SpecialEntry(parent, - labelpos = 'w', - label_text = 'Text (max 10 chars):', - validate = {'validator' : 'text', 'max' : 10}, - command = self.execute) - self._any.setentry('abc') - self._int = SpecialEntry(parent, - labelpos = 'w', - label_text = 'Int4:', - validate = 'int4') - self._int.setentry(1) - self._real = SpecialEntry(parent, - labelpos = 'w', - label_text = 'Real (max 2,5e+9):', - validate = {'validator' : 'real', 'max' : +2.5e+9}, - ) - self._real.setentry('+2.5e+6') - self._date = SpecialEntry(parent, - labelpos = 'w', - label_text = 'Date (dd.mm.yy):', - validate = 'date', - modifiedcommand = self.changed - ) - # Set entry to one week from now, using special intput format. - self._date.setentry('+7+') - - entries = (self._any, self._int, self._real, self._date) - - for entry in entries: - entry.pack(fill='x', expand=1, padx=10, pady=5) - Pmw.alignlabels(entries) - - self._any.component('entry').focus_set() - - def changed(self): - print 'Text changed, converted value is', self._date.getentry() - - def execute(self): - print 'Return pressed, value is', self._any.get() - - # This implements a custom validation routine. It simply checks - # if the string is of odd length. - def custom_validate(self, text): - print 'text:', text - if len(text) % 2 == 0: - return -1 - else: - return 1 - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/Spectrum.py b/Pmw/Pmw_1_2/demos/Spectrum.py deleted file mode 100644 index cfef9791..00000000 --- a/Pmw/Pmw_1_2/demos/Spectrum.py +++ /dev/null @@ -1,166 +0,0 @@ -title = 'Color spectrum demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import string -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - parent = Tkinter.Frame(parent) - parent.pack(padx=10, pady=10, fill='both', expand=1) - self.width = 350 - self.height = 250 - self.canvas = Tkinter.Canvas(parent, - width = self.width, height = self.height) - self.canvas.grid(row = 0, column = 0, columnspan = 2, sticky = 'news') - - self.numColors = Pmw.EntryField(parent, - labelpos = 'w', - label_text = 'Number of colors:', - entry_width = 5, - validate = 'numeric', - command = Pmw.busycallback(self.execute)) - self.numColors.grid(row = 1, column = 0, sticky = 'ew') - - self.correction = Pmw.EntryField(parent, - labelpos = 'w', - label_text = 'Correction:', - validate = 'real', - entry_width = 5, - command = Pmw.busycallback(self.execute)) - self.correction.grid(row = 1, column = 1, sticky = 'ew') - - self.saturation = Pmw.EntryField(parent, - labelpos = 'w', - label_text = 'Saturation:', - validate = 'real', - entry_width = 5, - command = Pmw.busycallback(self.execute)) - self.saturation.grid(row = 2, column = 0, sticky = 'ew') - - self.intensity = Pmw.EntryField(parent, - labelpos = 'w', - label_text = 'Intensity:', - validate = 'real', - entry_width = 5, - command = Pmw.busycallback(self.execute)) - self.intensity.grid(row = 2, column = 1, sticky = 'ew') - - self.extraOrange = Pmw.EntryField(parent, - labelpos = 'w', - label_text = 'Emphasize orange (0 or 1):', - validate = {'validator' : 'numeric', 'min' : 0, 'max' : 1}, - entry_width = 5, - command = Pmw.busycallback(self.execute)) - self.extraOrange.grid(row = 3, column = 0, sticky = 'ew') - - self.text = Pmw.EntryField(parent, - labelpos = 'w', - label_text = 'Text:', - entry_width = 20, - command = Pmw.busycallback(self.execute)) - self.text.grid(row = 4, column = 0, sticky = 'ew') - - self.brightness = Pmw.EntryField(parent, - labelpos = 'w', - label_text = 'Brightness:', - validate = 'real', - entry_width = 5, - command = Pmw.busycallback(self.execute)) - self.brightness.grid(row = 3, column = 1, sticky = 'ew') - - self.radiobuttons = Pmw.RadioSelect(parent, - command = Pmw.busycallback(self.radio_cb), - ) - self.radiobuttons.grid(row = 4, column = 1) - self.radiobuttons.add('Use saturation\nand intensity') - self.radiobuttons.add('Use\nbrightness') - - parent.grid_columnconfigure(0, weight = 1) - parent.grid_columnconfigure(1, weight = 1) - parent.grid_rowconfigure(0, weight = 1) - - Pmw.alignlabels((self.numColors, self.saturation, self.extraOrange)) - Pmw.alignlabels((self.correction, self.intensity, self.brightness)) - - # Set initial values for all entries. - self.numColors.setentry('64') - self.correction.setentry('1.0') - self.saturation.setentry('1.0') - self.intensity.setentry('1.0') - self.extraOrange.setentry('1') - self.brightness.setentry('0.7') - self.text.setentry('This is a test') - self.radiobuttons.invoke('Use saturation\nand intensity') - - self.execute() - - def radio_cb(self, value): - self.execute() - - def execute(self): - try: - numColors = string.atoi(self.numColors.get()) - correction = string.atof(self.correction.get()) - saturation = string.atof(self.saturation.get()) - intensity = string.atof(self.intensity.get()) - extraOrange = string.atof(self.extraOrange.get()) - brightness = string.atof(self.brightness.get()) - except ValueError: - self.numColors.bell() - return - - if numColors <= 0: - self.numColors.bell() - return - - self.canvas.delete('all') - - colorList = Pmw.Color.spectrum( - numColors, correction, saturation, intensity, extraOrange) - extent = 360.0 / numColors - - useBrightness = \ - (self.radiobuttons.getcurselection() == 'Use\nbrightness') - - if numColors == 1: - # Special case circle, since create_arc does not work when - # extent is 360. - background = colorList[0] - if useBrightness: - background = Pmw.Color.changebrightness( - self.canvas, background, brightness) - self.canvas.create_oval(10, 10, self.width - 10, self.height - 10, - fill = background, outline = background) - - for index in range(numColors): - start = index * extent - extent / 2 - background = colorList[index] - if useBrightness: - background = Pmw.Color.changebrightness( - self.canvas, background, brightness) - self.canvas.create_arc(10, 10, self.width - 10, self.height - 10, - start = start, extent = extent, - fill = background, outline = background) - - text = self.text.get() - self.canvas.create_text(self.width / 2, self.height / 3, text = text) - self.canvas.create_text(self.width / 2, self.height / 2, text = text) - self.canvas.create_text(self.width / 2, 2 * self.height / 3, text = text) - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/SpeedTest.py b/Pmw/Pmw_1_2/demos/SpeedTest.py deleted file mode 100644 index 589486bb..00000000 --- a/Pmw/Pmw_1_2/demos/SpeedTest.py +++ /dev/null @@ -1,60 +0,0 @@ -title = 'Test of the speed of creating Pmw megawidgets' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import time -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - self.parent = parent - - message = 'This is a test of the time\n' + \ - 'it takes to create 20 Pmw\nEntryField megawidgets.\n' + \ - 'Click on the button to create them.' - w = Tkinter.Label(parent, text = message) - w.pack(padx = 8, pady = 8) - - # Create button to run speed test. - w = Tkinter.Button(parent, - text = 'Create 20 EntryFields', - command = self.createEntries) - w.pack(padx = 8, pady = 8) - - def createEntries(self): - entryTop = Tkinter.Toplevel(self.parent) - - startClock = time.clock() - fields = [] - for num in range(20): - field = Pmw.EntryField(entryTop, - labelpos = 'w', - label_text='*' + ('*' * num), - hull_background = 'lightsteelblue', - label_background = 'lightsteelblue', - hull_highlightbackground = 'lightsteelblue', - label_highlightbackground = 'lightsteelblue', - entry_highlightbackground = 'lightsteelblue', - entry_background = 'aliceblue') - field.pack() - fields.append(field) - - Pmw.alignlabels(fields) - print 'Time to create 20 EntryFields:', \ - time.clock() - startClock, 'seconds' - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/SubClassing.py b/Pmw/Pmw_1_2/demos/SubClassing.py deleted file mode 100644 index f538b59e..00000000 --- a/Pmw/Pmw_1_2/demos/SubClassing.py +++ /dev/null @@ -1,128 +0,0 @@ -title = 'More examples of subclassing' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class ExtraMethods(Pmw.EntryField): - - # How to subclass a Pmw megawidget when you only want to add or - # override methods. - - def doubletext(self): - self.setvalue(self.getvalue() + ' ' + self.getvalue()) - -class OverrideInit(Pmw.EntryField): - - # How to subclass a Pmw megawidget when you want to define - # a new __init__ method. - - def __init__(self, textToAdd, parent = None, **kw): - self._textToAdd = textToAdd - apply(Pmw.EntryField.__init__, (self, parent), kw) - - def addtext(self): - self.setvalue(self.getvalue() + ' ' + self._textToAdd) - -class DefaultOptions(Pmw.EntryField): - - # How to subclass a Pmw megawidget when you only want to set - # existing options to new default values. - - def __init__(self, parent = None, **kw): - kw['label_foreground'] = 'blue' - kw['entry_background'] = 'white' - apply(Pmw.EntryField.__init__, (self, parent), kw) - -class NewOptions(Pmw.EntryField): - - # How to subclass a Pmw megawidget when you want to add new options. - - def __init__(self, parent=None , **kw): - - # Define the megawidget options. - optiondefs = ( - ('backgrounds', None, self._backgrounds), - ) - self.defineoptions(kw, optiondefs) - - # Initialise the base class (after defining the options). - Pmw.EntryField.__init__(self, parent) - - # Check keywords and initialise options. - self.initialiseoptions() - - def _backgrounds(self): - background = self['backgrounds'] - Pmw.Color.changecolor(self.component('hull'), background) - -class Demo: - def __init__(self, parent): - # Create and pack the megawidgets. - self._extraMethod = ExtraMethods(parent, - labelpos = 'w', - label_text = 'Sub class with extra method:', - value = 'Hello' - ) - self._overrideInit = OverrideInit('Again', parent, - labelpos = 'w', - label_text = 'Sub class with new __init__ method:', - value = 'Hello' - ) - self._defaultOptions = DefaultOptions(parent, - labelpos = 'w', - label_text = 'Sub class with new default options:', - value = 'Hello' - ) - - self._newOptions = NewOptions(parent, - labelpos = 'w', - label_text = 'Sub class with new option:', - value = 'Hello', - backgrounds = 'white', - ) - - entries = (self._extraMethod, self._overrideInit, - self._defaultOptions, self._newOptions) - - for entry in entries: - entry.pack(fill='x', expand=1, padx=10, pady=5) - Pmw.alignlabels(entries) - - bb = Pmw.ButtonBox(parent) - bb.add('Double text', command = self._doubleText) - bb.pack() - bb.add('Add text', command = self._addText) - bb.pack() - bb.add('White', command = self._changeColorWhite) - bb.pack() - bb.add('Green', command = self._changeColorGreen) - bb.pack() - - def _doubleText(self): - self._extraMethod.doubletext() - - def _addText(self): - self._overrideInit.addtext() - - def _changeColorWhite(self): - self._newOptions.configure(backgrounds = 'white') - - def _changeColorGreen(self): - self._newOptions.configure(backgrounds = 'green') - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/TextDialog.py b/Pmw/Pmw_1_2/demos/TextDialog.py deleted file mode 100644 index adec8214..00000000 --- a/Pmw/Pmw_1_2/demos/TextDialog.py +++ /dev/null @@ -1,75 +0,0 @@ -title = 'Pmw.TextDialog demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - # Create the dialog. - dialog = Pmw.TextDialog(parent, scrolledtext_labelpos = 'n', - title = 'My TextDialog', - defaultbutton = 0, - label_text = 'Lawyer jokes') - dialog.withdraw() - dialog.insert('end', jokes) - dialog.configure(text_state = 'disabled') - - # Create button to launch the dialog. - w = Tkinter.Button(parent, text = 'Show text dialog', - command = dialog.activate) - w.pack(padx = 8, pady = 8) - -jokes = """ -Q: What do you call 5000 dead lawyers at the bottom of the ocean? -A: A good start! - -Q: How can you tell when a lawyer is lying? -A: His lips are moving. - -Q: Why won't sharks attack lawyers? -A: Professional courtesy. - -Q: What do have when a lawyer is buried up to his neck in sand? -A: Not enough sand. - -Q: How do you get a lawyer out of a tree? -A: Cut the rope. - -Q: What is the definition of a shame (as in "that's a shame")? -A: When a bus load of lawyers goes off a cliff. - -Q: What is the definition of a "crying shame"? -A: There was an empty seat. - -Q: What do you get when you cross the Godfather with a lawyer? -A: An offer you can't understand. - -Q. What do lawyers use as contraceptives? -A. Their personalities. - -Q. What's brown and black and looks good on a lawyer? -A. A doberman. - -Q. Why are lawyers buried 12 feet underground? -A. Deep down their good. - -Q. What's the difference between a catfish and a lawyer? -A. One's a slimy scum-sucking scavenger, the other is just a fish. - -""" -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/TextDisplay.py b/Pmw/Pmw_1_2/demos/TextDisplay.py deleted file mode 100644 index 0eadf525..00000000 --- a/Pmw/Pmw_1_2/demos/TextDisplay.py +++ /dev/null @@ -1,78 +0,0 @@ -title = 'Demonstration of how to create a megawidget' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class TextDisplay(Pmw.MegaWidget): - - # Demo Pmw megawidget. - - def __init__(self, parent = None, **kw): - - # Define the megawidget options. - optiondefs = () - self.defineoptions(kw, optiondefs) - - # Initialise the base class (after defining the options). - Pmw.MegaWidget.__init__(self, parent) - - # Create the components. - interior = self.interior() - - self._text = self.createcomponent('text', - (), None, - Tkinter.Text, (interior,), state = 'disabled') - self._text.pack(side='left', fill='both', expand='yes') - - self._scrollbar = self.createcomponent('scrollbar', - (), None, - Tkinter.Scrollbar, (interior,), command = self._text.yview) - self._scrollbar.pack(side='right', fill='y') - self._text.configure(yscrollcommand = self._scrollbar.set) - - # Check keywords and initialise options. - self.initialiseoptions() - - def display(self, info): - self._text.configure(state = 'normal') - self._text.delete('1.0', 'end') - self._text.insert('1.0', info) - self._text.configure(state = 'disabled') - - def append(self, info): - self._text.configure(state = 'normal') - self._text.insert('end', info) - self._text.configure(state = 'disabled') - -class Demo: - def __init__(self, parent): - # Create and pack the megawidget. - text = TextDisplay(parent, - text_background = 'aliceblue', - text_width = 40, - text_height = 10, - text_wrap = 'none', - ) - text.pack(fill = 'both', expand = 1) - text.display('This is an example of a simple Pmw megawidget.\n\n' + - 'Public attributes of the Tkinter module:\n\n') - for name in dir(Tkinter): - if name[0] != '_': - text.append(' ' + name + '\n') - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/TimeCounter.py b/Pmw/Pmw_1_2/demos/TimeCounter.py deleted file mode 100644 index 7be1eb36..00000000 --- a/Pmw/Pmw_1_2/demos/TimeCounter.py +++ /dev/null @@ -1,40 +0,0 @@ -title = 'Pmw.TimeCounter demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import string -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - self._time = Pmw.TimeCounter(parent, - labelpos = 'w', - label_text = 'HH:MM:SS', - min = '00:00:00', - max = '23:59:59') - self._time.pack(padx=10, pady=5) - - button = Tkinter.Button(parent, text = 'Show', command = self.show) - button.pack() - - def show(self): - stringVal = self._time.getstring() - intVal = self._time.getint() - print stringVal + ' (' + str(intVal) + ')' - - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/demos/WidgetDestroy.py b/Pmw/Pmw_1_2/demos/WidgetDestroy.py deleted file mode 100644 index a62fa28c..00000000 --- a/Pmw/Pmw_1_2/demos/WidgetDestroy.py +++ /dev/null @@ -1,36 +0,0 @@ -title = 'Demonstration of Pmw megawidget destruction' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - # Create and pack an EntryField. - self.entryfield = Pmw.EntryField(parent, - command = self.execute, - value = 'Press to destroy me', - entry_width = 30) - self.entryfield.pack(fill='x', expand=1, padx=10, pady=5) - - self.entryfield.component('entry').focus_set() - - def execute(self): - print 'Return pressed, destroying EntryField.' - self.entryfield.destroy() - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/doc/AboutDialog.gif b/Pmw/Pmw_1_2/doc/AboutDialog.gif deleted file mode 100644 index 2d60dc59..00000000 Binary files a/Pmw/Pmw_1_2/doc/AboutDialog.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/AboutDialog.html b/Pmw/Pmw_1_2/doc/AboutDialog.html deleted file mode 100644 index 8f487d5b..00000000 --- a/Pmw/Pmw_1_2/doc/AboutDialog.html +++ /dev/null @@ -1,286 +0,0 @@ - - - - - - Pmw.AboutDialog reference manual - - - - -

Pmw.AboutDialog

- -
-
-

Name

-

Pmw.AboutDialog() - - window to display version and contact information -

- - -
-

Inherits

-Pmw.MessageDialog
-
-

Description

-

- An about dialog is a dialog window which displays information - about the application, such as name, version, copyright and - contact details.

- -

The text of the message is constructed from the application name - (given by the applicationname option) followed by the values - supplied in the most recent calls to Pmw.aboutversion(), - Pmw.aboutcopyright() and Pmw.aboutcontact() functions.

- -

The icon of the message defaults to 'info', but may be changed - using the icon_bitmap component option.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
activatecommand -
-If this is callable, it will be called whenever the megawidget is - activated by a call to activate(). The default is None.

- - -
- -
applicationname -
-Initialisation option. The name of application, to be dispayed in the dialog body and in - the window title if the title option is not given. The default is ''.

- - -
- -
borderx -
-Initialisation option. The padding to the left and right of the text message and icon. The default is 20.

- - -
- -
bordery -
-Initialisation option. The padding above and below the text message and icon. The default is 20.

- - -
- -
buttonboxpos -
-Initialisation option. Specifies on which side of the dialog window to place the button - box. Must be one of 'n', 's', 'e' or 'w'. The default is 's'.

- - -
- -
buttons -
-This must be a tuple or a list and specifies the names on the - buttons in the button box. The default is ('Close',).

- - -
- -
command -
-Specifies a function to call whenever a button in the button box - is invoked or the window is deleted by the window manager. The - function is called with a single argument, which is the name of - the button which was invoked, or None if the window was deleted - by the window manager.

-

If the value of command is not callable, the default behaviour - is to deactivate the window if it is active, or withdraw the - window if it is not active. If it is deactivated, deactivate() - is called with the button name or None as described above. The default is None.

- - - -
- -
deactivatecommand -
-If this is callable, it will be called whenever the megawidget is - deactivated by a call to deactivate(). The default is None.

- - -
- -
defaultbutton -
-Specifies the default button in the button box. If the <Return> - key is hit when the dialog has focus, the default button will be - invoked. If defaultbutton is None, there will be no default - button and hitting the <Return> key will have no effect. The default is 0.

- - -
- -
iconmargin -
-Initialisation option. The padding between the text message and icon. The default is 20.

- - -
- -
iconpos -
-Initialisation option. Specifies on which side of the text message to place the icon. - Must be one of 'n', 's', 'e' or 'w'. The default is 'w'.

- - -
- -
master -
-This is used by the activate() method to control whether the - window is made transient during modal dialogs. See the - activate() method. The default is 'parent'.

- - -
- -
separatorwidth -
-Initialisation option. If this is greater than 0, a separator line with the specified - width will be created between the button box and the child site, - as a component named separator. Since the default border of the - button box and child site is raised, this option does not - usually need to be set for there to be a visual separation between - the button box and child site. The default is 0.

- - -
- -
title -
-This is the title that the window manager displays in the title - bar of the window. The default is None.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
buttonbox -
-This is the button box containing the buttons for the dialog. By - default it is created with the options - (hull_borderwidth = 1, hull_relief = 'raised'). By default, this component is a Pmw.ButtonBox.

- - -
- -
dialogchildsite -
-This is the child site for the dialog, which may be used to - specialise the megawidget by creating other widgets within it. By - default it is created with the options - (borderwidth = 1, relief = 'raised'). By default, this component is a Tkinter.Frame.

- - -
- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Toplevel.

- - -
- -
icon -
-If the iconpos option is not None, this component is created - to contain the icon label for the dialog. To display a bitmap as - an icon, set the icon_bitmap component option to any of the - forms acceptable to Tk, such as 'warning' or 'error'. By default, this component is a Tkinter.Label.

- - -
- -
message -
-The label to contain the text message for the dialog. To set - the text, use the message_text component option. By default, this component is a Tkinter.Label.

- - -
- -
separator -
-If the separatorwidth initialisation option is non-zero, the - separator component is the line dividing the area between the - button box and the child site. By default, this component is a Tkinter.Frame.

- - -
-
- -

Methods

-This megawidget has no methods of its own. -For a description of its inherited methods, see the -manual for its base class -Pmw.MessageDialog. -

-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-        # Create dialog.
-        Pmw.aboutversion('9.9')
-        Pmw.aboutcopyright('Copyright My Company 1999\nAll rights reserved')
-        Pmw.aboutcontact(
-            'For information about this application contact:\n' +
-            '  My Help Desk\n' +
-            '  Phone: +61 2 9876 5432\n' +
-            '  email: help@my.company.com.au'
-        )
-        self.about = Pmw.AboutDialog(parent, applicationname = 'My Application')
-        self.about.withdraw()
-
-        # Create button to launch the dialog.
-        w = Tkinter.Button(parent, text = 'Show about dialog',
-                command = self.execute)
-        w.pack(padx = 8, pady = 8)
-
-    def execute(self):
-        self.about.show()
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 18 May 2002 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/Balloon.gif b/Pmw/Pmw_1_2/doc/Balloon.gif deleted file mode 100644 index e8bc9b81..00000000 Binary files a/Pmw/Pmw_1_2/doc/Balloon.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/Balloon.html b/Pmw/Pmw_1_2/doc/Balloon.html deleted file mode 100644 index 012f9c39..00000000 --- a/Pmw/Pmw_1_2/doc/Balloon.html +++ /dev/null @@ -1,429 +0,0 @@ - - - - - - Pmw.Balloon reference manual - - - - -

Pmw.Balloon

- -
-
-

Name

-

Pmw.Balloon() - - display "tool tips" for a number of widgets -

- - -
-

Inherits

-Pmw.MegaToplevel
-
-

Description

-

- A balloon megawidget can be used to give short help messages to - the user when they place the mouse over a button or other widget - for a short time. It can also be used to display help messages - for canvas or text items.

- -

One balloon megawidget can be used to display help for many - widgets or items. For each widget or item that requires balloon - help, the bind() or bindtag() method is used to specify the - help text that should be displayed.

- -

The help message is displayed in a popup balloon window when the - mouse remains over the widget or item for a short time. The popup - balloon is withdrawn when the mouse leaves the widget or item, or - any mouse buttons are pressed.

- -

The position of the popup balloon is configurable and may appear - either relative to the widget or item or relative to the position - of the mouse.

- -

The popup balloon is displayed without any window manager - decorations.

- -

The megawidget can cooperate with a Pmw.MessageBar to display a - single-line help message as well as the balloon help.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
activatecommand -
-If this is callable, it will be called whenever the megawidget is - activated by a call to activate(). The default is None.

- - -
- -
deactivatecommand -
-If this is callable, it will be called whenever the megawidget is - deactivated by a call to deactivate(). The default is None.

- - -
- -
initwait -
-The number of milliseconds delay between when the mouse enters a - widget or item and when the popup balloon window should be - displayed. The default is 500.

- - -
- -
master -
-This is used by the activate() method to control whether the - window is made transient during modal dialogs. See the - activate() method. The default is 'parent'.

- - -
- -
relmouse -
-This may be one of 'both', 'x', 'y' or 'none' and - indicates that the top left corner of the popup balloon window - should be placed relative to the current position of the mouse - rather than relative to the bottom left corner of the widget or - item (the default). The positioning may be set for the horizontal - (x) and vertical (y) axes independently. The default is 'none'.

- - -
- -
state -
-This may be one of 'both', 'balloon', 'status' or 'none' - and indicates whether the help message should be displayed in the - popup balloon window, in an associated messagebar (via the - statuscommand option), or both. The default is 'both'.

- - -
- -
statuscommand -
-This specifies a function to call when the mouse enters a widget - or item bound to this balloon megawidget. To configure a - Pmw.MessageBar to display help, set this option to the helpmessage - method of the messagebar. The default is None.

- - -
- -
title -
-This is the title that the window manager displays in the title - bar of the window. The default is None.

- - -
- -
xoffset -
-This specifies the horizontal offset of the position of the left - side of the popup balloon window relative the point determined by - the relmouse option. The default is 20.

- - -
- -
yoffset -
-This specifies the vertical offset of the position of the top of - the popup balloon window relative the point determined by the - relmouse option. The default is 1.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Toplevel.

- - -
- -
label -
-This component displays the text of the help message in the popup - balloon window. By default it is created with a 'lightyellow' - background, a 'black' foreground and is 'left' justified. By default, this component is a Tkinter.Label.

- - -
-
- -

Methods

-Only methods specific to this megawidget are described below. -For a description of its inherited methods, see the -manual for its base class -Pmw.MegaToplevel. -

- -
bind(widget, balloonHelp, statusHelp = None)
-Create bindings for widget so that balloon help and/or status - help is displayed when the mouse enters the widget. The balloon - help message is given by balloonHelp and the status help message - is given by statusHelp. If balloonHelp is None, no balloon - is displayed. If statusHelp is not set, it defaults to - balloonHelp. Any previous bindings for this widget are removed.

- - -
- -
clearstatus()
-Clear the text in the associated messagebar by passing None to - the statuscommand function.

- - -
- -
showstatus(statusHelp)
-Set the text in the associated messagebar by passing statusHelp - to the statuscommand function.

- - -
- -
tagbind(widget, tagOrItem, balloonHelp, statusHelp = None)
-Create bindings for the tag or item specified by tagOrItem in - the text or canvas widget so that balloon help and/or status - help is displayed when the mouse enters the tag or item. The - balloon help message is given by balloonHelp and the status help - message is given by statusHelp. If balloonHelp is None, no - balloon is displayed. If statusHelp is not set, it defaults to - balloonHelp. Any previous bindings for this tag or item are - removed.

- - -
- -
tagunbind(widget, tagOrItem)
-Remove the balloon help bindings from the tag or item specified by - tagOrItem in the text or canvas widget.

-

Note that tagunbind() must be called when deleting a canvas - item, so that the popup balloon window can be withdrawn if it was - triggered by the item. (Unfortunately this can not be automated - as is done for widgets since Tk does not support <Destroy> - bindings on canvas items, so there is no way that Pmw.Balloon can - be notified of the deletion of an item.)

- - - -
- -
unbind(widget)
-Remove the balloon help bindings from widget.

- - -
-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-        # Create the Balloon.
-        self.balloon = Pmw.Balloon(parent)
-
-        # Create some widgets and megawidgets with balloon help.
-        frame = Tkinter.Frame(parent)
-        frame.pack(padx = 10, pady = 5)
-        field = Pmw.EntryField(frame,
-                labelpos = 'nw',
-                label_text = 'Command:')
-        field.setentry('mycommand -name foo')
-        field.pack(side = 'left', padx = 10)
-        self.balloon.bind(field, 'Command to\nstart/stop',
-                'Enter the shell command to control')
-
-        start = Tkinter.Button(frame, text='Start')
-        start.pack(side='left', padx = 10)
-        self.balloon.bind(start, 'Start the command')
-
-        stop = Tkinter.Button(frame, text='Stop')
-        stop.pack(side='left', padx = 10)
-        self.balloon.bind(stop, 'Stop the command')
-
-        self.suicide = Tkinter.Button(frame, text='Kill me soon!',
-            command = self.killButton)
-        self.suicide.pack(side='left', padx = 10)
-        self.balloon.bind(self.suicide, 'Watch this button disappear!')
-
-        scrolledCanvas = Pmw.ScrolledCanvas(parent,
-                canvas_width = 300,
-                canvas_height = 115,
-        )
-        scrolledCanvas.pack()
-        canvas = scrolledCanvas.component('canvas')
-        self.canvas = canvas
-
-        # Create some canvas items and individual help.
-        item = canvas.create_arc(5, 5, 35, 35, fill = 'red', extent = 315)
-        self.balloon.tagbind(canvas, item, 'This is help for\nan arc item')
-        item = canvas.create_bitmap(20, 150, bitmap = 'question')
-        self.balloon.tagbind(canvas, item, 'This is help for\na bitmap')
-        item = canvas.create_line(50, 60, 70, 80, 85, 20, width = 5)
-        self.balloon.tagbind(canvas, item, 'This is help for\na line item')
-        item = canvas.create_text(10, 90, text = 'Canvas items with balloons',
-                anchor = 'nw', font = field.cget('entry_font'))
-        self.balloon.tagbind(canvas, item, 'This is help for\na text item')
-
-        # Create two canvas items which have the same tag and which use
-        # the same help.
-        canvas.create_rectangle(100, 10, 170, 50, fill = 'aliceblue',
-                tags = 'TAG1')
-        self.bluecircle = canvas.create_oval(110, 30, 160, 80, fill = 'blue',
-                tags = 'TAG1')
-        self.balloon.tagbind(canvas, 'TAG1',
-                'This is help for the two blue items' + '\n' * 10 +
-                    'It is very, very big.',
-                'This is help for the two blue items')
-        item = canvas.create_text(180, 10, text = 'Delete',
-                anchor = 'nw', font = field.cget('entry_font'))
-        self.balloon.tagbind(canvas, item,
-                'After 2 seconds,\ndelete the blue circle')
-        canvas.tag_bind(item, '<ButtonPress>', self._canvasButtonpress)
-        scrolledCanvas.resizescrollregion()
-
-        scrolledText = Pmw.ScrolledText(parent,
-                text_width = 32,
-                text_height = 4,
-                text_wrap = 'none',
-        )
-        scrolledText.pack(pady = 5)
-        text = scrolledText.component('text')
-        self.text = text
-
-        text.insert('end',
-                'This is a text widget with ', '',
-                ' balloon', 'TAG1',
-                '\nhelp. Find the ', '',
-                ' text ', 'TAG1',
-                ' tagged with', '',
-                ' help.', 'TAG2',
-                '\n', '',
-                'Remove tag 1.', 'TAG3',
-                '\nAnother line.\nAnd another', '',
-        )
-        text.tag_configure('TAG1', borderwidth = 2, relief = 'sunken')
-        text.tag_configure('TAG3', borderwidth = 2, relief = 'raised')
-
-        self.balloon.tagbind(text, 'TAG1',
-                'There is one secret\nballoon help.\nCan you find it?')
-        self.balloon.tagbind(text, 'TAG2',
-                'Well done!\nYou found it!')
-        self.balloon.tagbind(text, 'TAG3',
-                'After 2 seconds\ndelete the tag')
-        text.tag_bind('TAG3', '<ButtonPress>', self._textButtonpress)
-
-        frame = Tkinter.Frame(parent)
-        frame.pack(padx = 10)
-        self.toggleBalloonVar = Tkinter.IntVar()
-        self.toggleBalloonVar.set(1)
-        toggle = Tkinter.Checkbutton(frame,
-                variable = self.toggleBalloonVar,
-                text = 'Balloon help', command = self.toggle)
-        toggle.pack(side = 'left', padx = 10)
-        self.balloon.bind(toggle, 'Toggle balloon help\non and off')
-
-        self.toggleStatusVar = Tkinter.IntVar()
-        self.toggleStatusVar.set(1)
-        toggle = Tkinter.Checkbutton(frame,
-                variable = self.toggleStatusVar,
-                text = 'Status help', command = self.toggle)
-        toggle.pack(side = 'left', padx = 10)
-        self.balloon.bind(toggle,
-                'Toggle status help on and off, on and off' + '\n' * 10 +
-                    'It is very, very big, too.',
-                'Toggle status help on and off')
-
-        # Create and pack the MessageBar.
-        messageBar = Pmw.MessageBar(parent,
-                entry_width = 40,
-                entry_relief='groove',
-                labelpos = 'w',
-                label_text = 'Status:')
-        messageBar.pack(fill = 'x', expand = 1, padx = 10, pady = 5)
-
-        # Configure the balloon to display its status messages in the
-        # message bar.
-        self.balloon.configure(statuscommand = messageBar.helpmessage)
-
-    def toggle(self):
-        if self.toggleBalloonVar.get():
-            if self.toggleStatusVar.get():
-                self.balloon.configure(state = 'both')
-            else:
-                self.balloon.configure(state = 'balloon')
-        else:
-            if self.toggleStatusVar.get():
-                self.balloon.configure(state = 'status')
-            else:
-                self.balloon.configure(state = 'none')
-
-    def killButton(self):
-        # Test for old bug when destroying widgets 1) while the
-        # balloon was up and 2) during the initwait period.
-        print 'Destroying button in 2 seconds'
-        self.suicide.after(2000, self.suicide.destroy)
-
-    def _canvasButtonpress(self, event):
-        print 'Destroying blue circle in 2 seconds'
-        self.canvas.after(2000, self.deleteBlueCircle)
-
-    def deleteBlueCircle(self):
-        self.balloon.tagunbind(self.canvas, self.bluecircle)
-        self.canvas.delete(self.bluecircle)
-
-    def _textButtonpress(self, event):
-        print 'Deleting the text tag in 2 seconds'
-        self.text.after(2000, self.deleteTextTag)
-
-    def deleteTextTag(self):
-        self.balloon.tagunbind(self.text, 'TAG1')
-        self.text.tag_delete('TAG1')
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 20 May 2002 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/Blt.html b/Pmw/Pmw_1_2/doc/Blt.html deleted file mode 100644 index 99869840..00000000 --- a/Pmw/Pmw_1_2/doc/Blt.html +++ /dev/null @@ -1,135 +0,0 @@ - - - - - - Pmw.Blt reference manual - - - - -

Pmw.Blt

- -
-

Name

-

Pmw.Blt - - interface to some BLT widgets and commands

-

- - - -
-

Description

-

- This module contains function interfaces to the BLT busy command - as well as the classes Pmw.Blt.Vector, Pmw.Blt.Graph, - Pmw.Blt.Stripchart and Pmw.Blt.Tabset, which are interfaces to - the vector, graph, stripchart and tabset commands of version 2.4 - of the BLT extension to Tk. The interfaces are complete except - for Pmw.Blt.Vector where several creation options, methods and - operations have not been implemented.

- -

The blt graph and barchart widgets are essentially the same and so - only the graph widget has been ported. The element_create() - method is not implememted for Pmw.Blt.Graph, so instead:

-
  • to create a line element, use the line_create() method and

    - -
  • -
  • to create a bar element, use the bar_create() method.

    - -
- -

To operate on elements, use the element_*() methods, such as - element_bind(), element_activate(), etc.

- -

Note: Full documentation of Pmw.Blt.Graph is available in - A User's Guide to Pmw.Blt - written by Bjørn Ove Thue and Hans Petter Langtangen. - You can also download - the full HTML document - of the guide for local viewing.

- -

- - -
-

Functions

-The following functions are available.

-
-
Pmw.Blt.busy_forget(window)
- - Interface to the BLT busy forget command.

- -

- - -
-
Pmw.Blt.busy_hold(window, cursor = None)
- - Interface to the BLT busy hold command.

- -

- - -
-
Pmw.Blt.busy_release(window)
- - Interface to the BLT busy release command.

- -

- - -
-
Pmw.Blt.haveblt(window)
- - Return true if any commands in the BLT extension are available.

- -

- - -
-
Pmw.Blt.havebltbusy(window)
- - Return true if the BLT busy command is available.

- -

- - -
-
Pmw.Blt.vector_expr(expression)
- - Interface to the BLT vector expr command.

- -

- - -
-
Pmw.Blt.vector_names(pattern = None)
- - Interface to the BLT vector names command.

- -

- - -
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 25 May 2002 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/ButtonBox.gif b/Pmw/Pmw_1_2/doc/ButtonBox.gif deleted file mode 100644 index 402b6b0e..00000000 Binary files a/Pmw/Pmw_1_2/doc/ButtonBox.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/ButtonBox.html b/Pmw/Pmw_1_2/doc/ButtonBox.html deleted file mode 100644 index 2075f42f..00000000 --- a/Pmw/Pmw_1_2/doc/ButtonBox.html +++ /dev/null @@ -1,306 +0,0 @@ - - - - - - Pmw.ButtonBox reference manual - - - - -

Pmw.ButtonBox

- -
-
-

Name

-

Pmw.ButtonBox() - - manager megawidget for buttons -

- - -
-

Inherits

-Pmw.MegaWidget
-
-

Description

-

- A button box is a container megawidget which manages a number of - buttons. One of these buttons may be specified as the default and - it will be displayed with the platform specific appearance for a - default button. The buttons may be laid out either horizontally - or vertically.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
labelmargin -
-Initialisation option. If the labelpos option is not None, this specifies the - distance between the label component and the rest of the - megawidget. The default is 0.

- - -
- -
labelpos -
-Initialisation option. Specifies where to place the label component. If not - None, it should be a concatenation of one or two of the - letters 'n', 's', 'e' and 'w'. The first letter - specifies on which side of the megawidget to place the label. - If a second letter is specified, it indicates where on that - side to place the label. For example, if labelpos is 'w', - the label is placed in the center of the left hand side; if - it is 'wn', the label is placed at the top of the left - hand side; if it is 'ws', the label is placed at the - bottom of the left hand side.

-

If None, a label component is not created. The default is None.

- - - -
- -
orient -
-Initialisation option. Specifies the orientation of the button box. This may be - 'horizontal' or 'vertical'. The default is 'horizontal'.

- - -
- -
padx -
-Initialisation option. Specifies a padding distance to leave between each button in the x - direction and also between the buttons and the outer edge of the - button box. The default is 3.

- - -
- -
pady -
-Initialisation option. Specifies a padding distance to leave between each button in the y - direction and also between the buttons and the outer edge of the - button box. The default is 3.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
frame -
-If the label component has been created (that is, the labelpos - option is not None), the frame component is created to act as - the container of the buttons created by the add() and - insert() methods. If there is no label component, then no - frame component is created and the hull component acts as the - container. By default, this component is a Tkinter.Frame.

- - -
- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Frame.

- - -
- -
label -
-If the labelpos option is not None, this component is - created as a text label for the megawidget. See the - labelpos option for details. Note that to set, for example, - the text option of the label, you need to use the label_text - component option. By default, this component is a Tkinter.Label.

- - -
-
-

Dynamic components

-

- Button components are created dynamically by the add() and - insert() methods. By default, the buttons are of type - Tkinter.Button and are created with a component group of - Button.

-

- - - -
- -

Methods

-Only methods specific to this megawidget are described below. -For a description of its inherited methods, see the -manual for its base class -Pmw.MegaWidget. -

- -
add(componentName, **kw)
-Add a button to the end of the button box as a component named - componentName. Any keyword arguments present will be passed to the - constructor when creating the button. If the text keyword - argument is not given, the text option of the button defaults to - componentName. The method returns the component widget.

- - -
- -
alignbuttons(when = 'later')
-Set the widths of all the buttons to be the same as the width of - the widest button. If when is 'later', this will occur when the - interpreter next becomes idle, otherwise the resizing will occur - immediately.

- - -
- -
button(buttonIndex)
-Return the button specified by buttonIndex, which may have any - of the forms accepted by the index() method.

- - -
- -
delete(index)
-Delete the button given by index from the button box. index - may have any of the forms accepted by the index() method.

- - -
- -
index(index, forInsert = 0)
-Return the numerical index of the button corresponding to index. - This may be specified in any of the following forms:

-
name
Specifies the button named name.

- -
-
number
Specifies the button numerically, where 0 corresponds to - the left (or top) button.

- -
-
Pmw.END
Specifies the right (or bottom) button.

- -
-
Pmw.DEFAULT
Specifies the current default button.

- -
-

If forInsert is true, Pmw.END returns the number of buttons rather - than the index of the last button.

- - - -
- -
insert(componentName, beforeComponent = 0, **kw)
-Add a button to the button box as a component named - componentName. The button is added just before the button - specified by beforeComponent, which may have any of the forms - accepted by the index() method. Any keyword arguments present - will be passed to the constructor when creating the button. If - the text keyword argument is not given, the text option of the - button defaults to componentName. To add a button to the end of - the button box, use add(). The method returns the component - widget.

- - -
- -
invoke(index = Pmw.DEFAULT, noFlash = 0)
-Invoke the callback command associated with the button specified - by index and return the value returned by the callback. - Unless noFlash is true, flash the button to - indicate to the user that something happened. - index may have any of the forms accepted by the index() method.

- - -
- -
numbuttons()
-Return the number of buttons in the button box.

- - -
- -
setdefault(index)
-Set the default button to the button given by index. This - causes the specified button to be displayed with the platform - specific appearance for a default button. If index is None, - there will be no default button. index may have any of the - forms accepted by the index() method.

- - -
-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-        # Create and pack the ButtonBox.
-        self.buttonBox = Pmw.ButtonBox(parent,
-                labelpos = 'nw',
-                label_text = 'ButtonBox:',
-                frame_borderwidth = 2,
-                frame_relief = 'groove')
-        self.buttonBox.pack(fill = 'both', expand = 1, padx = 10, pady = 10)
-
-        # Add some buttons to the ButtonBox.
-        self.buttonBox.add('OK', command = self.ok)
-        self.buttonBox.add('Apply', command = self.apply)
-        self.buttonBox.add('Cancel', command = self.cancel)
-
-        # Set the default button (the one executed when <Return> is hit).
-        self.buttonBox.setdefault('OK')
-        parent.bind('<Return>', self._processReturnKey)
-        parent.focus_set()
-
-        # Make all the buttons the same width.
-        self.buttonBox.alignbuttons()
-
-    def _processReturnKey(self, event):
-        self.buttonBox.invoke()
-
-    def ok(self):
-        print 'You clicked on OK'
-
-    def apply(self):
-        print 'You clicked on Apply'
-
-    def cancel(self):
-        print 'You clicked on Cancel'
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 24 May 1998 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/Color.html b/Pmw/Pmw_1_2/doc/Color.html deleted file mode 100644 index e004f85e..00000000 --- a/Pmw/Pmw_1_2/doc/Color.html +++ /dev/null @@ -1,326 +0,0 @@ - - - - - - Pmw.Color reference manual - - - - -

Pmw.Color

- -
-

Name

-

Pmw.Color - - contains functions for handling colors and color schemes

-

- - - -
-

Description

-

- This module is a set of functions for manipulating colors and for - modifying the color scheme of an application or a widget. Many of - the functions in this module take or return colors. These values - may represent colors in the following ways:

-
name
a standard color name, eg 'orange' or '#ffa500'

- -
-
rgb
a 3-element sequence of red, green and blue intensities - each between 0.0 (dark) and 1.0 (light), eg [1.0, 0.6, 0.0].

- -
-
hsi
a 3-element sequence (hue, saturation, - intensity). The value of hue is between 0.0 and 2pi - (6.28318) giving a range of colors covering, in order, red, - orange, yellow green, cyan, blue, magenta and back to red. - The value of saturation is between 0.0 (grey) and 1.0 - (brilliant) and the value of intensity is between 0.0 (dark) - and 1.0 (bright).

- -
- -

As used in these functions, the brightness of a color is the - perceived grey level of the color as registered by the human eye. - For example, even though the colors red, blue and yellow have the - same intensity (1.0), they have different brightnesses, 0.299, - 0.114 and 0.886 respectively, reflecting the different way these - colors appear to the eye. The brightness of a color is a value - between 0.0 (dark) and 1.0 (bright).

- -

A color scheme is a set of colors defined for each of the - default color options in the Tk option database. Color schemes - can be used in two ways. Firstly, using Pmw.Color.setscheme(), - the Tk option database can be set to the values in the color - scheme. This will not have any effect on currently existing - widgets, but any new widgets created after setting the options - will have these colors as their defaults. Secondly, using - Pmw.Color.changecolor() the color scheme can be used to change - the colors of a widget and all its child widgets.

- -

A color scheme is specified by defining one or more color options - (one of the defined options must be background). Not all - options need be specified - if any options are not defined, they - are calculated from the other colors. These are the options used - by a color scheme, together with their values if not specified:

-
 background:            (must be specified)
- foreground:            black
- activeForeground:      same as foreground
- insertBackground:      same as foreground
- selectForeground:      same as foreground
- highlightColor:        same as foreground
- disabledForeground:    between fg and bg but closer to bg
- highlightBackground:   same as background
- activeBackground:      a little lighter that bg
- selectBackground:      a little darker that bg
- troughColor:           a little darker that bg
- selectColor:           yellow
- - -

There are many functions in this module. As well as - Pmw.Color.setscheme() and Pmw.Color.changecolor(), some of the - most useful are Pmw.Color.spectrum(), - Pmw.Color.changebrightness() and - Pmw.Color.getdefaultpalette().

- -

- - -
-

Functions

-The following functions are available.

-
-
Pmw.Color.average(rgb1, rgb2, fraction)
- - Return an rgb color fraction of the way "between" the colors - rgb1 and rgb2, where fraction must be between 0.0 and - 1.0. If fraction is close to 0.0, then the color returned - will be close to rgb1. If it is close to 1.0, then the color - returned will be close to rgb2. If it is near 0.5, then the - color returned will be half way between the two colors.

- -

- - -
-
Pmw.Color.bhi2saturation(brightness, hue, intensity)
- - Return the saturation of the color represented by brightness, - hue and intensity.

- -

- - -
-
Pmw.Color.bordercolors(root, colorName)
- - Return a tuple (light, dark) of color names that can be used as - the light and dark border shadows on a widget where the background - is colorName. This is the same method that Tk uses for shadows - when drawing reliefs on widget borders. The root argument is - only used to query Tk for the rgb values of colorName.

- -

- - -
-
Pmw.Color.changebrightness(root, colorName, brightness)
- - Find the hue of the color colorName and return a color of this - hue with the required brightness. If brightness is None, - return the name of color with the given hue and with saturation - and intensity both 1.0. The root argument is only used to - query Tk for the rgb values of colorName.

- -

- - -
-
Pmw.Color.changecolor(widget, background = None, **kw)
- - Change the color of widget and all its child widgets according - to the color scheme specified by the other arguments. This is done - by modifying all of the color options of existing widgets that - have the default value. The color options are the lower case - versions of those described in the color scheme section. Any - options which are different to the previous color scheme (or the - defaults, if this is the first call) are not changed.

- -

For example to change a widget to have a red color scheme with a - white foreground:

- -
 Pmw.Color.changecolor(widget,
-     background = 'red3', foreground = 'white')
- -

The colors of widgets created after this call will not be - affected.

- -

Note that widget must be a Tk widget or toplevel. To change the - color of a Pmw megawidget, use it's hull component. For example:

- -
 widget = megawidget.component('hull')
- Pmw.Color.changecolor(widget, background = 'red3')
- -

- - -
-
Pmw.Color.correct(rgb, correction)
- - Return the "corrected" value of rgb. This can be used to - correct for dull monitors. If correction is less than 1.0, - the color is dulled. If correction is greater than 1.0, the - color is brightened.

- -

- - -
-
Pmw.Color.getdefaultpalette(root)
- - Return a dictionary of the default values of the color options - described in the color scheme section.

- -

To do this, a few widgets are created as children of root, their - defaults are queried, and then the widgets are destroyed. (Tk - supplies no other way to get widget default values.)

- -

Note that root must be a Tk widget or toplevel. To use a Pmw - megawidget as the root, use it's hull component. For example:

- -
 root = megawidget.component('hull')
- Pmw.Color.getdefaultpalette(root)
- -

- - -
-
Pmw.Color.hsi2rgb(hue, saturation, intensity)
- - Return the rgb representation of the color represented by hue, - saturation and intensity.

- -

- - -
-
Pmw.Color.hue2name(hue, brightness = None)
- - Return the name of the color with the specified hue and - brightness. If hue is None, return a grey of the requested - brightness. Otherwise, the value of hue should be as described - above. If brightness is None, return the name of color with - the given hue and with saturation and intensity both 1.0.

- -

- - -
-
Pmw.Color.name2rgb(root, colorName, asInt = 0)
- - Return colorName as an rgb value. If asInt is true, then - the elements of the return sequence are in the range 0 to - 65535 rather than 0.0 to 1.0. The root argument is only - used to query Tk for the rgb values of colorName.

- -

- - -
-
Pmw.Color.rgb2brightness(rgb)
- - Return the brightness of the color represented by rgb.

- -

- - -
-
Pmw.Color.rgb2hsi(rgb)
- - Return a tuple (hue, saturation, intensity) corresponding to - the color specified by the rgb sequence.

- -

- - -
-
Pmw.Color.rgb2name(rgb)
- - Return the name of the color represented by rgb as a string of - the form '#RRGGBB' suitable for use with Tk color functions.

- -

- - -
-
Pmw.Color.setscheme(root, background = None, **kw)
- - Set the color scheme for the application by setting default colors - (in the Tk option database of the root window of root) according - to the color scheme specified by the other arguments. This will - affect the initial colours of all widgets created after the call - to this function.

- -

For example to initialise an application to have a red color - scheme with a white foreground:

- -
 Pmw.Color.setscheme(root,
-     background = 'red3', foreground = 'white')
- -

This function does not modify the colors of already existing - widgets. Use Pmw.Color.changecolor() to do this.

- -

Note that root must be a Tk widget or toplevel. To use the Tk - option database of the root window of a Pmw megawidget, use the - megawidget's hull component. For example:

- -
 root = megawidget.component('hull')
- Pmw.Color.setscheme(root, background = 'red3')
- -

- - -
-
Pmw.Color.spectrum(numColors, correction = 1.0, saturation = 1.0, intensity = 1.0, extraOrange = 1, returnHues = 0)
- - Return a list of numColors different colors making up a - spectrum. If extraOrange is false, the colors are evenly - spaced by hue from one end of the spectrum (red) to the other - (magenta). If extraOrange is true, the hues are not quite - evenly spaced - the hues around orange are emphasised, thus - preventing the spectrum from appearing to have to many cool - hues.

- -

If returnHues is false, the return values are the names of the - colors represented by the hues together with saturation and - intensity and corrected by correction.

- -

If returnHues is true, the return values are hues.

- -

- - -
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 25 May 2002 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/ComboBox.gif b/Pmw/Pmw_1_2/doc/ComboBox.gif deleted file mode 100644 index 31fee77c..00000000 Binary files a/Pmw/Pmw_1_2/doc/ComboBox.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/ComboBox.html b/Pmw/Pmw_1_2/doc/ComboBox.html deleted file mode 100644 index 0be8d68c..00000000 --- a/Pmw/Pmw_1_2/doc/ComboBox.html +++ /dev/null @@ -1,363 +0,0 @@ - - - - - - Pmw.ComboBox reference manual - - - - -

Pmw.ComboBox

- -
-
-

Name

-

Pmw.ComboBox() - - dropdown or simple combination box -

- - -
-

Inherits

-Pmw.MegaWidget
-
-

Description

-

- A combobox contains an entry field and an associated scrolled - listbox. When an item in the listbox is selected, it is displayed - in the entry field. Optionally, the user may also edit the entry - field directly.

- -

For a simple combobox, the scrolled listbox is displayed beneath - the entry field. For a dropdown combobox (the default), the - scrolled listbox is displayed in a window which pops up beneath - the entry field when the user clicks on an arrow button on the - right of the entry field. Either style allows an optional label.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
autoclear -
-Initialisation option. If both autoclear and history are true, clear the entry field - whenever <Return> is pressed, after adding the value to the - history list. The default is 0.

- - -
- -
buttonaspect -
-Initialisation option. The width of the arrow button as a proportion of the height. The - height of the arrow button is set to the height of the entry - widget. The default is 1.0.

- - -
- -
dropdown -
-Initialisation option. Specifies whether the combobox should be dropdown or simple. The default is 1.

- - -
- -
fliparrow -
-Initialisation option. If true, the arrow button is draw upside down when the listbox is - being displayed. Used only in dropdown megawidgets. The default is 0.

- - -
- -
history -
-Initialisation option. When <Return> is pressed in the entry field, the current value - of the entry field is appended to the listbox if history is - true. The default is 1.

- - -
- -
labelmargin -
-Initialisation option. If the labelpos option is not None, this specifies the - distance between the label component and the rest of the - megawidget. The default is 0.

- - -
- -
labelpos -
-Initialisation option. Specifies where to place the label component. If not - None, it should be a concatenation of one or two of the - letters 'n', 's', 'e' and 'w'. The first letter - specifies on which side of the megawidget to place the label. - If a second letter is specified, it indicates where on that - side to place the label. For example, if labelpos is 'w', - the label is placed in the center of the left hand side; if - it is 'wn', the label is placed at the top of the left - hand side; if it is 'ws', the label is placed at the - bottom of the left hand side.

-

If None, a label component is not created. The default is None.

- - - -
- -
listheight -
-Initialisation option. The height, in pixels, of the dropdown listbox. The default is 200.

- - -
- -
selectioncommand -
-The function to call when an item is selected. - If this function takes a long time to run, and you want the entry - field to be updated quickly, call update_idletasks() at the - beginning of the function. Alternatively, wrap the function using - Pmw.busycallback(). The default is None.

- - -
- -
sticky -
-Initialisation option. The default is 'ew'.

- - -
- -
unique -
-Initialisation option. If both unique and history are true, the current value of the - entry field is not added to the listbox if it is already in the - list. The default is 1.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
arrowbutton -
-In a dropdown combobox, the button to popup the listbox. By default, this component is a Tkinter.Canvas.

- - -
- -
entryfield -
-The entry field where the current selection is displayed. By default, this component is a Pmw.EntryField.

- - -
- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Frame.

- - -
- -
label -
-If the labelpos option is not None, this component is - created as a text label for the megawidget. See the - labelpos option for details. Note that to set, for example, - the text option of the label, you need to use the label_text - component option. By default, this component is a Tkinter.Label.

- - -
- -
popup -
-In a dropdown combobox, the dropdown window. By default, this component is a Tkinter.Toplevel.

- - -
- -
scrolledlist -
-The scrolled listbox which displays the items to select. By default, this component is a Pmw.ScrolledListBox.

- - -
-
-

Component aliases

-Sub-components of components of this megawidget -may be accessed via the following aliases.

-
entry -
-Alias for entryfield_entry. -
-
listbox -
-Alias for scrolledlist_listbox. -
-
- -

Methods

-Only methods specific to this megawidget are described below. -For a description of its inherited methods, see the -manual for its base class -Pmw.MegaWidget. -In addition, methods from the following classes -are forwarded by this megawidget. -Methods from Pmw.ScrolledListBox -are forwarded to the -scrolledlist component. -Methods from Pmw.EntryField -are forwarded to the -entryfield component. -Forwarded methods are searched in the order given. -

- -
bbox(index)
-This method is explicitly forwarded to the scrolledlist - component's bbox() method. Without this explicit forwarding, - the bbox() method (aliased to grid_bbox()) of the hull would - be invoked, which is probably not what the programmer intended.

- - -
- -
clear()
-Delete all items from the scrolled listbox and delete all text - from the entry widget.

- - -
- -
get(first = None, last = None)
-This is the same as the get() method of the scrolledlist - component, except that if first is None then - the value of the entry field is returned.

- - -
- -
invoke()
-If a dropdown combobox, display the dropdown listbox. In a simple - combobox, select the currently selected item in the listbox, - call the selectioncommand and return the result.

- - -
- -
selectitem(index, setentry = 1)
-Select the item in the listbox specified by index which may be - either one of the items in the listbox or the integer index of one - of the items in the listbox.

-

If setentry is true, also set the entry field to the selected - item.

- - - -
- -
size()
-This method is explicitly forwarded to the scrolledlist - component's size() method. Without this explicit forwarding, - the size() method (aliased to grid_size()) of the hull would - be invoked, which is probably not what the programmer intended.

- - -
-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-        parent.configure(background = 'white')
-
-        # Create and pack the widget to be configured.
-        self.target = Tkinter.Label(parent,
-                relief = 'sunken',
-                padx = 20,
-                pady = 20,
-        )
-        self.target.pack(fill = 'x', padx = 8, pady = 8)
-
-        # Create and pack the simple ComboBox.
-        words = ('Monti', 'Python', 'ik', 'den', 'Holie', 'Grailen', '(Bok)')
-        simple = Pmw.ComboBox(parent,
-                label_text = 'Simple ComboBox:',
-                labelpos = 'nw',
-                selectioncommand = self.changeText,
-                scrolledlist_items = words,
-                dropdown = 0,
-        )
-        simple.pack(side = 'left', fill = 'both',
-                expand = 1, padx = 8, pady = 8)
-
-        # Display the first text.
-        first = words[0]
-        simple.selectitem(first)
-        self.changeText(first)
-
-        # Create and pack the dropdown ComboBox.
-        colours = ('cornsilk1', 'snow1', 'seashell1', 'antiquewhite1',
-                'bisque1', 'peachpuff1', 'navajowhite1', 'lemonchiffon1',
-                'ivory1', 'honeydew1', 'lavenderblush1', 'mistyrose1')
-        dropdown = Pmw.ComboBox(parent,
-                label_text = 'Dropdown ComboBox:',
-                labelpos = 'nw',
-                selectioncommand = self.changeColour,
-                scrolledlist_items = colours,
-        )
-        dropdown.pack(side = 'left', anchor = 'n',
-                fill = 'x', expand = 1, padx = 8, pady = 8)
-
-        # Display the first colour.
-        first = colours[0]
-        dropdown.selectitem(first)
-        self.changeColour(first)
-
-    def changeColour(self, colour):
-        print 'Colour: ' + colour
-        self.target.configure(background = colour)
-
-    def changeText(self, text):
-        print 'Text: ' + text
-        self.target.configure(text = text)
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 1 November 1998 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/ComboBoxDialog.gif b/Pmw/Pmw_1_2/doc/ComboBoxDialog.gif deleted file mode 100644 index 011fde57..00000000 Binary files a/Pmw/Pmw_1_2/doc/ComboBoxDialog.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/ComboBoxDialog.html b/Pmw/Pmw_1_2/doc/ComboBoxDialog.html deleted file mode 100644 index e139f11c..00000000 --- a/Pmw/Pmw_1_2/doc/ComboBoxDialog.html +++ /dev/null @@ -1,286 +0,0 @@ - - - - - - Pmw.ComboBoxDialog reference manual - - - - -

Pmw.ComboBoxDialog

- -
-
-

Name

-

Pmw.ComboBoxDialog() - - selection dialog displaying a list and an entry field -

- - -
-

Inherits

-Pmw.Dialog
-
-

Description

-

- A combobox dialog is a dialog window which displays a list and - an entry field which can be used to prompt the user for a value.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
activatecommand -
-If this is callable, it will be called whenever the megawidget is - activated by a call to activate(). The default is None.

- - -
- -
borderx -
-Initialisation option. The padding to the left and right of the combobox. The default is 10.

- - -
- -
bordery -
-Initialisation option. The padding above and below the combobox. The default is 10.

- - -
- -
buttonboxpos -
-Initialisation option. Specifies on which side of the dialog window to place the button - box. Must be one of 'n', 's', 'e' or 'w'. The default is 's'.

- - -
- -
buttons -
-This must be a tuple or a list and specifies the names on the - buttons in the button box. The default is ('OK',).

- - -
- -
command -
-Specifies a function to call whenever a button in the button box - is invoked or the window is deleted by the window manager. The - function is called with a single argument, which is the name of - the button which was invoked, or None if the window was deleted - by the window manager.

-

If the value of command is not callable, the default behaviour - is to deactivate the window if it is active, or withdraw the - window if it is not active. If it is deactivated, deactivate() - is called with the button name or None as described above. The default is None.

- - - -
- -
deactivatecommand -
-If this is callable, it will be called whenever the megawidget is - deactivated by a call to deactivate(). The default is None.

- - -
- -
defaultbutton -
-Specifies the default button in the button box. If the <Return> - key is hit when the dialog has focus, the default button will be - invoked. If defaultbutton is None, there will be no default - button and hitting the <Return> key will have no effect. The default is None.

- - -
- -
master -
-This is used by the activate() method to control whether the - window is made transient during modal dialogs. See the - activate() method. The default is 'parent'.

- - -
- -
separatorwidth -
-Initialisation option. If this is greater than 0, a separator line with the specified - width will be created between the button box and the child site, - as a component named separator. Since the default border of the - button box and child site is raised, this option does not - usually need to be set for there to be a visual separation between - the button box and child site. The default is 0.

- - -
- -
title -
-This is the title that the window manager displays in the title - bar of the window. The default is None.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
buttonbox -
-This is the button box containing the buttons for the dialog. By - default it is created with the options - (hull_borderwidth = 1, hull_relief = 'raised'). By default, this component is a Pmw.ButtonBox.

- - -
- -
combobox -
-The combobox for the user to enter a value. By default it is - created using the option dropdown = 0. By default, this component is a Pmw.ComboBox.

- - -
- -
dialogchildsite -
-This is the child site for the dialog, which may be used to - specialise the megawidget by creating other widgets within it. By - default it is created with the options - (borderwidth = 1, relief = 'raised'). By default, this component is a Tkinter.Frame.

- - -
- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Toplevel.

- - -
- -
separator -
-If the separatorwidth initialisation option is non-zero, the - separator component is the line dividing the area between the - button box and the child site. By default, this component is a Tkinter.Frame.

- - -
-
-

Component aliases

-Sub-components of components of this megawidget -may be accessed via the following aliases.

-
entry -
-Alias for combobox_entry. -
-
label -
-Alias for combobox_label. -
-
listbox -
-Alias for combobox_listbox. -
-
scrolledlist -
-Alias for combobox_scrolledlist. -
-
- -

Methods

-Only methods specific to this megawidget are described below. -For a description of its inherited methods, see the -manual for its base class -Pmw.Dialog. -In addition, methods from the -Pmw.ComboBox class -are forwarded by this megawidget to the -combobox component. -

- -
bbox(index)
-This method is explicitly forwarded to the combobox component's - bbox() method. Without this explicit forwarding, the bbox() - method (aliased to grid_bbox()) of the hull would be invoked, - which is probably not what the programmer intended.

- - -
- -
size()
-This method is explicitly forwarded to the combobox component's - size() method. Without this explicit forwarding, the size() - method (aliased to grid_size()) of the hull would be invoked, - which is probably not what the programmer intended.

- - -
-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-        # Create the dialog.
-        self.dialog = Pmw.ComboBoxDialog(parent,
-            title = 'My ComboBoxDialog',
-            buttons = ('OK', 'Cancel'),
-            defaultbutton = 'OK',
-            combobox_labelpos = 'n',
-            label_text = 'What do you think of Pmw?',
-            scrolledlist_items = ('Cool man', 'Cool', 'Good', 'Bad', 'Gross'))
-        self.dialog.withdraw()
-
-        # Create button to launch the dialog.
-        w = Tkinter.Button(parent,
-                text = 'Show combo box dialog',
-                command = self.doit)
-        w.pack(padx = 8, pady = 8)
-
-    def doit(self):
-        result = self.dialog.activate()
-        print 'You clicked on', result, self.dialog.get()
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 18 May 2002 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/Counter.gif b/Pmw/Pmw_1_2/doc/Counter.gif deleted file mode 100644 index 20c33222..00000000 Binary files a/Pmw/Pmw_1_2/doc/Counter.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/Counter.html b/Pmw/Pmw_1_2/doc/Counter.html deleted file mode 100644 index a52595e8..00000000 --- a/Pmw/Pmw_1_2/doc/Counter.html +++ /dev/null @@ -1,455 +0,0 @@ - - - - - - Pmw.Counter reference manual - - - - -

Pmw.Counter

- -
-
-

Name

-

Pmw.Counter() - - entry field with up and down arrow buttons -

- - -
-

Inherits

-Pmw.MegaWidget
-
-

Description

-

- A counter contains an entry field and two arrow buttons to - increment and decrement the value in the entry field. Standard - counting types include numbers, times and dates. A user defined - counting function may also be supplied for specialised counting. - Counting can be used in combination with the entry field's - validation. The components may be laid out horizontally or - vertically.

- -

Each time an arrow button is pressed the value displayed in the - entry field is incremented or decremented by the value of the - increment option. If the new value is invalid (according to the - entry field's validate option, perhaps due to exceeding minimum - or maximum limits), the old value is restored.

- -

When an arrow button is pressed and the value displayed is not an - exact multiple of the increment, it is "truncated" up or down to - the nearest increment.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
autorepeat -
-If true, the counter will continue to count up or down while an - arrow button is held pressed down. The default is 1.

- - -
- -
buttonaspect -
-Initialisation option. Specifies the width of the arrow buttons as a proportion of their - height. Values less than 1.0 will produce thin arrow buttons. - Values greater than 1.0 will produce fat arrow buttons. The default is 1.0.

- - -
- -
datatype -
-Specifies how the counter should count up and down.

-

The most general way to specify the datatype option is as a - dictionary. The kind of counting is specified by the 'counter' - dictionary field, which may be either a function or the name of - one of the standard counters described below. If the dictionary - does not have a 'counter' field, the field defaults to - 'numeric'.

- -

Any other fields in the dictionary are passed on to the counter - function as keyword arguments.

- -

If datatype is not a dictionary, then it is equivalent to - specifying it as a dictionary with a single 'counter' field. - For example, datatype = 'real' is equivalent to - datatype = {'counter' : 'real'}.

- -

The standard counters are:

- -
'numeric'
An integer number, as accepted by string.atol().

- -
-
'integer'
Same as 'numeric'.

- -
-
'real'
A real number, as accepted by string.atof(). This - counter accepts a 'separator' argument, which specifies - the character used to represent the decimal point. The - default 'separator' is '.'.

- -
-
'time'
A time specification, as accepted by - Pmw.timestringtoseconds(). This counter accepts a - 'separator' argument, which specifies the character used to - separate the time fields. The default separator is ':'. - This counter also accepts a 'time24' argument. If this is - true, the time value is converted to a value between - '00:00:00' and '23:59:59'. The default is false.

- -
-
'date'
A date specification, as accepted by - Pmw.datestringtojdn(). This counter accepts a 'separator' - argument, which specifies the character used to separate the - three date fields. The default is '/'. This counter also - accepts a 'format' argument, which is passed to - Pmw.datestringtojdn() to specify the desired ordering of the - fields. The default is 'ymd'. - This counter also accepts a 'yyyy' argument. If this is - false, the year field will be displayed as the year within the - century, otherwise it will be fully displayed. In both cases - it will be displayed with at least 2 digits, using leading - zeroes. The default is false.

- -
-

If the 'counter' dictionary field is a function, then it will be - called whenever the counter is to be incremented or decremented. - The function is called with at least three arguments, the first - three being (text, factor, increment), where text is the - current contents of the entry field, factor is 1 when - incrementing or -1 when decrementing, and increment is the - value of the increment megawidget option.

- -

The other arguments are keyword arguments made up of the fields of - the datatype dictionary (excluding the 'counter' field).

- -

The counter function should return a string representing the - incremented or decremented value. It should raise a - ValueError exception if the text is invalid. In this case the - bell is rung and the entry text is not changed.

- -

The default for datatype is numeric.

- - - -
- -
increment -
-Specifies how many units should be added or subtracted when the - counter is incremented or decremented. If the currently displayed - value is not a multiple of increment, the value is changed to - the next multiple greater or less than the current value.

-

For the number datatypes, the value of increment is a number. - For the 'time' datatype, the value is in seconds. For the - 'date' datatype, the value is in days. The default is 1.

- - - -
- -
initwait -
-Specifies the initial delay (in milliseconds) before a depressed - arrow button automatically starts to repeat counting. The default is 300.

- - -
- -
labelmargin -
-Initialisation option. If the labelpos option is not None, this specifies the - distance between the label component and the rest of the - megawidget. The default is 0.

- - -
- -
labelpos -
-Initialisation option. Specifies where to place the label component. If not - None, it should be a concatenation of one or two of the - letters 'n', 's', 'e' and 'w'. The first letter - specifies on which side of the megawidget to place the label. - If a second letter is specified, it indicates where on that - side to place the label. For example, if labelpos is 'w', - the label is placed in the center of the left hand side; if - it is 'wn', the label is placed at the top of the left - hand side; if it is 'ws', the label is placed at the - bottom of the left hand side.

-

If None, a label component is not created. The default is None.

- - - -
- -
orient -
-Initialisation option. Specifies whether the arrow buttons should appear to the left and - right of the entry field ('horizontal') or above and below - ('vertical'). The default is 'horizontal'.

- - -
- -
padx -
-Initialisation option. Specifies a padding distance to leave around the arrow buttons in - the x direction. The default is 0.

- - -
- -
pady -
-Initialisation option. Specifies a padding distance to leave around the arrow buttons in - the y direction. The default is 0.

- - -
- -
repeatrate -
-Specifies the delay (in milliseconds) between automatic counts - while an arrow button is held pressed down. The default is 50.

- - -
- -
sticky -
-Initialisation option. The default is 'ew'.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
downarrow -
-The arrow button used for decrementing the counter. Depending on - the value of orient, it will appear on the left or below the - entry field. By default, this component is a Tkinter.Canvas. Its component group is Arrow.

- - -
- -
entryfield -
-The entry field widget where the text is entered, displayed and - validated. By default, this component is a Pmw.EntryField.

- - -
- -
frame -
-If the label component has been created (that is, the labelpos - option is not None), the frame component is created to act as - the container of the entry field and arrow buttons. If there is - no label component, then no frame component is created and the - hull component acts as the container. In either case the border - around the container of the entry field and arrow buttons will be - raised (but not around the label). By default, this component is a Tkinter.Frame.

- - -
- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Frame.

- - -
- -
label -
-If the labelpos option is not None, this component is - created as a text label for the megawidget. See the - labelpos option for details. Note that to set, for example, - the text option of the label, you need to use the label_text - component option. By default, this component is a Tkinter.Label.

- - -
- -
uparrow -
-The arrow button used for incrementing the counter. Depending on - the value of orient, it will appear on the right or above the - entry field. By default, this component is a Tkinter.Canvas. Its component group is Arrow.

- - -
-
-

Component aliases

-Sub-components of components of this megawidget -may be accessed via the following aliases.

-
entry -
-Alias for entryfield_entry. -
-
- -

Methods

-Only methods specific to this megawidget are described below. -For a description of its inherited methods, see the -manual for its base class -Pmw.MegaWidget. -In addition, methods from the -Pmw.EntryField class -are forwarded by this megawidget to the -entryfield component. -

- -
decrement()
-Decrement the counter once, as if the down arrow had been pressed.

- - -
- -
increment()
-Increment the counter once, as if the up arrow had been pressed.

- - -
-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-        # Need to use long ints here because on the Macintosh the maximum size
-        # of an integer is smaller than the value returned by time.time().
-        now = (long(time.time()) / 300) * 300
-
-        # Create the Counters.
-        self._date = Pmw.Counter(parent,
-                labelpos = 'w',
-                label_text = 'Date (4-digit year):',
-                entryfield_value =
-                        time.strftime('%d/%m/%Y', time.localtime(now)),
-                entryfield_command = self.execute,
-                entryfield_validate = {'validator' : 'date', 'format' : 'dmy'},
-                datatype = {'counter' : 'date', 'format' : 'dmy', 'yyyy' : 1})
-
-        self._isodate = Pmw.Counter(parent,
-                labelpos = 'w',
-                label_text = 'ISO-Date (4-digit year):',
-                entryfield_value =
-                        time.strftime('%Y-%m-%d', time.localtime(now)),
-                entryfield_command = self.execute,
-                entryfield_validate = {'validator' : 'date', 'format' : 'ymd',
-                        'separator' : '-' },
-                datatype = {'counter' : 'date', 'format' : 'ymd', 'yyyy' : 1,
-                        'separator' : '-' })
-
-        self._time = Pmw.Counter(parent,
-                labelpos = 'w',
-                label_text = 'Time:',
-                entryfield_value =
-                        time.strftime('%H:%M:%S', time.localtime(now)),
-                entryfield_validate = {'validator' : 'time',
-                        'min' : '00:00:00', 'max' : '23:59:59',
-                        'minstrict' : 0, 'maxstrict' : 0},
-                datatype = {'counter' : 'time', 'time24' : 1},
-                increment=5*60)
-        self._real = Pmw.Counter(parent,
-                labelpos = 'w',
-                label_text = 'Real (with comma)\nand extra\nlabel lines:',
-                label_justify = 'left',
-                entryfield_value = '1,5',
-                datatype = {'counter' : 'real', 'separator' : ','},
-                entryfield_validate = {'validator' : 'real',
-                        'min' : '-2,0', 'max' : '5,0',
-                        'separator' : ','},
-                increment = 0.1)
-        self._custom = Pmw.Counter(parent,
-                labelpos = 'w',
-                label_text = 'Custom:',
-                entryfield_value = specialword[:4],
-                datatype = _custom_counter,
-                entryfield_validate = _custom_validate)
-        self._int = Pmw.Counter(parent,
-                labelpos = 'w',
-                label_text = 'Vertical integer:',
-                orient = 'vertical',
-                entry_width = 2,
-                entryfield_value = 50,
-                entryfield_validate = {'validator' : 'integer',
-                        'min' : 0, 'max' : 99}
-        )
-
-        counters = (self._date, self._isodate, self._time, self._real,
-                self._custom)
-        Pmw.alignlabels(counters)
-
-        # Pack them all.
-        for counter in counters:
-            counter.pack(fill='both', expand=1, padx=10, pady=5)
-        self._int.pack(padx=10, pady=5)
-
-    def execute(self):
-        print 'Return pressed, value is', self._date.get()
-
-specialword = 'Monti Python ik den Holie Grailen (Bok)'
-
-def _custom_validate(text):
-    if string.find(specialword, text) == 0:
-        return 1
-    else:
-        return -1
-
-def _custom_counter(text, factor, increment):
-    # increment is ignored here.
-    if string.find(specialword, text) == 0:
-        length = len(text)
-        if factor == 1:
-            if length >= len(specialword):
-                raise ValueError, 'maximum length reached'
-            return specialword[:length + 1]
-        else:
-            if length == 0:
-                raise ValueError, 'empty string'
-            return specialword[:length - 1]
-    else:
-        raise ValueError, 'bad string ' + text
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 24 May 1998 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/CounterDialog.gif b/Pmw/Pmw_1_2/doc/CounterDialog.gif deleted file mode 100644 index dd833420..00000000 Binary files a/Pmw/Pmw_1_2/doc/CounterDialog.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/CounterDialog.html b/Pmw/Pmw_1_2/doc/CounterDialog.html deleted file mode 100644 index ec8ed83f..00000000 --- a/Pmw/Pmw_1_2/doc/CounterDialog.html +++ /dev/null @@ -1,299 +0,0 @@ - - - - - - Pmw.CounterDialog reference manual - - - - -

Pmw.CounterDialog

- -
-
-

Name

-

Pmw.CounterDialog() - - selection dialog displaying a counter -

- - -
-

Inherits

-Pmw.Dialog
-
-

Description

-

- A counter dialog is a dialog window which displays a counter - which can be used to prompt the user for a value.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
activatecommand -
-If this is callable, it will be called whenever the megawidget is - activated by a call to activate(). The default is None.

- - -
- -
borderx -
-Initialisation option. The padding to the left and right of the counter. The default is 20.

- - -
- -
bordery -
-Initialisation option. The padding above and below the counter. The default is 20.

- - -
- -
buttonboxpos -
-Initialisation option. Specifies on which side of the dialog window to place the button - box. Must be one of 'n', 's', 'e' or 'w'. The default is 's'.

- - -
- -
buttons -
-This must be a tuple or a list and specifies the names on the - buttons in the button box. The default is ('OK',).

- - -
- -
command -
-Specifies a function to call whenever a button in the button box - is invoked or the window is deleted by the window manager. The - function is called with a single argument, which is the name of - the button which was invoked, or None if the window was deleted - by the window manager.

-

If the value of command is not callable, the default behaviour - is to deactivate the window if it is active, or withdraw the - window if it is not active. If it is deactivated, deactivate() - is called with the button name or None as described above. The default is None.

- - - -
- -
deactivatecommand -
-If this is callable, it will be called whenever the megawidget is - deactivated by a call to deactivate(). The default is None.

- - -
- -
defaultbutton -
-Specifies the default button in the button box. If the <Return> - key is hit when the dialog has focus, the default button will be - invoked. If defaultbutton is None, there will be no default - button and hitting the <Return> key will have no effect. The default is None.

- - -
- -
master -
-This is used by the activate() method to control whether the - window is made transient during modal dialogs. See the - activate() method. The default is 'parent'.

- - -
- -
separatorwidth -
-Initialisation option. If this is greater than 0, a separator line with the specified - width will be created between the button box and the child site, - as a component named separator. Since the default border of the - button box and child site is raised, this option does not - usually need to be set for there to be a visual separation between - the button box and child site. The default is 0.

- - -
- -
title -
-This is the title that the window manager displays in the title - bar of the window. The default is None.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
buttonbox -
-This is the button box containing the buttons for the dialog. By - default it is created with the options - (hull_borderwidth = 1, hull_relief = 'raised'). By default, this component is a Pmw.ButtonBox.

- - -
- -
counter -
-The counter for the user to enter a value. By default, this component is a Pmw.Counter.

- - -
- -
dialogchildsite -
-This is the child site for the dialog, which may be used to - specialise the megawidget by creating other widgets within it. By - default it is created with the options - (borderwidth = 1, relief = 'raised'). By default, this component is a Tkinter.Frame.

- - -
- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Toplevel.

- - -
- -
separator -
-If the separatorwidth initialisation option is non-zero, the - separator component is the line dividing the area between the - button box and the child site. By default, this component is a Tkinter.Frame.

- - -
-
-

Component aliases

-Sub-components of components of this megawidget -may be accessed via the following aliases.

-
entry -
-Alias for counter_entryfield_entry. -
-
entryfield -
-Alias for counter_entryfield. -
-
label -
-Alias for counter_label. -
-
- -

Methods

-Only methods specific to this megawidget are described below. -For a description of its inherited methods, see the -manual for its base class -Pmw.Dialog. -In addition, methods from the -Pmw.Counter class -are forwarded by this megawidget to the -counter component. -

- -
deleteentry(first, last = None)
-Delete text from the counter's entry widget. An alias for - component('entry').delete().

- - -
- -
indexentry(index)
-An alias for component('entry').index().

- - -
- -
insertentry(index, text)
-Insert text into the counter's entry widget. An alias for - component('entry').insert().

- - -
-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-        # Create the dialog to prompt for the number of times to ring the bell.
-        self.dialog = Pmw.CounterDialog(parent,
-            label_text = 'Enter the number of times to\n' + \
-                    'sound the bell (1 to 5)\n',
-            counter_labelpos = 'n',
-            entryfield_value = 2,
-            counter_datatype = 'numeric',
-            entryfield_validate =
-                {'validator' : 'numeric', 'min' : 1, 'max' : 5},
-            buttons = ('OK', 'Cancel'),
-            defaultbutton = 'OK',
-            title = 'Bell ringing',
-            command = self.execute)
-        self.dialog.withdraw()
-
-        # Create button to launch the dialog.
-        w = Tkinter.Button(parent, text = 'Show counter dialog',
-                command = self.dialog.activate)
-        w.pack(padx = 8, pady = 8)
-
-    def execute(self, result):
-        if result is None or result == 'Cancel':
-            print 'Bell ringing cancelled'
-            self.dialog.deactivate()
-        else:
-            count = self.dialog.get()
-            if not self.dialog.valid():
-                print 'Invalid entry: "' + count + '"'
-            else:
-                print 'Ringing the bell ' + count + ' times'
-                for num in range(string.atoi(count)):
-                    if num != 0:
-                        self.dialog.after(200)
-                    self.dialog.bell()
-                self.dialog.deactivate()
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 18 May 2002 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/Dialog.gif b/Pmw/Pmw_1_2/doc/Dialog.gif deleted file mode 100644 index 34834576..00000000 Binary files a/Pmw/Pmw_1_2/doc/Dialog.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/Dialog.html b/Pmw/Pmw_1_2/doc/Dialog.html deleted file mode 100644 index 1e3c8886..00000000 --- a/Pmw/Pmw_1_2/doc/Dialog.html +++ /dev/null @@ -1,286 +0,0 @@ - - - - - - Pmw.Dialog reference manual - - - - -

Pmw.Dialog

- -
-
-

Name

-

Pmw.Dialog() - - toplevel window with button box -

- - -
-

Inherits

-Pmw.MegaToplevel
-
-

Description

-

- A dialog is a toplevel window composed of a button box and a child - site area. The child site area can be used to specialise the - megawidget by creating other widgets within it. This can be done - by using this class directly or by deriving from it.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
activatecommand -
-If this is callable, it will be called whenever the megawidget is - activated by a call to activate(). The default is None.

- - -
- -
buttonboxpos -
-Initialisation option. Specifies on which side of the dialog window to place the button - box. Must be one of 'n', 's', 'e' or 'w'. The default is 's'.

- - -
- -
buttons -
-This must be a tuple or a list and specifies the names on the - buttons in the button box. The default is ('OK',).

- - -
- -
command -
-Specifies a function to call whenever a button in the button box - is invoked or the window is deleted by the window manager. The - function is called with a single argument, which is the name of - the button which was invoked, or None if the window was deleted - by the window manager.

-

If the value of command is not callable, the default behaviour - is to deactivate the window if it is active, or withdraw the - window if it is not active. If it is deactivated, deactivate() - is called with the button name or None as described above. The default is None.

- - - -
- -
deactivatecommand -
-If this is callable, it will be called whenever the megawidget is - deactivated by a call to deactivate(). The default is None.

- - -
- -
defaultbutton -
-Specifies the default button in the button box. If the <Return> - key is hit when the dialog has focus, the default button will be - invoked. If defaultbutton is None, there will be no default - button and hitting the <Return> key will have no effect. The default is None.

- - -
- -
master -
-This is used by the activate() method to control whether the - window is made transient during modal dialogs. See the - activate() method. The default is 'parent'.

- - -
- -
separatorwidth -
-Initialisation option. If this is greater than 0, a separator line with the specified - width will be created between the button box and the child site, - as a component named separator. Since the default border of the - button box and child site is raised, this option does not - usually need to be set for there to be a visual separation between - the button box and child site. The default is 0.

- - -
- -
title -
-This is the title that the window manager displays in the title - bar of the window. The default is None.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
buttonbox -
-This is the button box containing the buttons for the dialog. By - default it is created with the options - (hull_borderwidth = 1, hull_relief = 'raised'). By default, this component is a Pmw.ButtonBox.

- - -
- -
dialogchildsite -
-This is the child site for the dialog, which may be used to - specialise the megawidget by creating other widgets within it. By - default it is created with the options - (borderwidth = 1, relief = 'raised'). By default, this component is a Tkinter.Frame.

- - -
- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Toplevel.

- - -
- -
separator -
-If the separatorwidth initialisation option is non-zero, the - separator component is the line dividing the area between the - button box and the child site. By default, this component is a Tkinter.Frame.

- - -
-
- -

Methods

-Only methods specific to this megawidget are described below. -For a description of its inherited methods, see the -manual for its base class -Pmw.MegaToplevel. -

- -
interior()
-Return the child site for the dialog. This is the same as - component('dialogchildsite').

- - -
- -
invoke(index = Pmw.DEFAULT)
-Invoke the command specified by the command option as if the - button specified by index had been pressed and return the - result. index may have any of the forms accepted by the - Pmw.ButtonBox index() method.

- - -
-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-        # Create two buttons to launch the dialog.
-        w = Tkinter.Button(parent, text = 'Show application modal dialog',
-                command = self.showAppModal)
-        w.pack(padx = 8, pady = 8)
-
-        w = Tkinter.Button(parent, text = 'Show global modal dialog',
-                command = self.showGlobalModal)
-        w.pack(padx = 8, pady = 8)
-
-        w = Tkinter.Button(parent, text = 'Show dialog with "no grab"',
-                command = self.showDialogNoGrab)
-        w.pack(padx = 8, pady = 8)
-
-        w = Tkinter.Button(parent, text =
-                    'Show toplevel window which\n' +
-                    'will not get a busy cursor',
-                command = self.showExcludedWindow)
-        w.pack(padx = 8, pady = 8)
-
-        # Create the dialog.
-        self.dialog = Pmw.Dialog(parent,
-            buttons = ('OK', 'Apply', 'Cancel', 'Help'),
-            defaultbutton = 'OK',
-            title = 'My dialog',
-            command = self.execute)
-        self.dialog.withdraw()
-
-        # Add some contents to the dialog.
-        w = Tkinter.Label(self.dialog.interior(),
-            text = 'Pmw Dialog\n(put your widgets here)',
-            background = 'black',
-            foreground = 'white',
-            pady = 20)
-        w.pack(expand = 1, fill = 'both', padx = 4, pady = 4)
-
-        # Create the window excluded from showbusycursor.
-        self.excluded = Pmw.MessageDialog(parent,
-            title = 'I still work',
-            message_text =
-                'This window will not get\n' +
-                'a busy cursor when modal dialogs\n' +
-                'are activated.  In addition,\n' +
-                'you can still interact with\n' +
-                'this window when a "no grab"\n' +
-                'modal dialog is displayed.')
-        self.excluded.withdraw()
-        Pmw.setbusycursorattributes(self.excluded.component('hull'),
-            exclude = 1)
-
-    def showAppModal(self):
-        self.dialog.activate(geometry = 'centerscreenalways')
-
-    def showGlobalModal(self):
-        self.dialog.activate(globalMode = 1)
-
-    def showDialogNoGrab(self):
-        self.dialog.activate(globalMode = 'nograb')
-
-    def showExcludedWindow(self):
-        self.excluded.show()
-
-    def execute(self, result):
-        print 'You clicked on', result
-        if result not in ('Apply', 'Help'):
-            self.dialog.deactivate(result)
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 18 May 2002 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/EntryField.gif b/Pmw/Pmw_1_2/doc/EntryField.gif deleted file mode 100644 index d9eeb8b2..00000000 Binary files a/Pmw/Pmw_1_2/doc/EntryField.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/EntryField.html b/Pmw/Pmw_1_2/doc/EntryField.html deleted file mode 100644 index 5417f144..00000000 --- a/Pmw/Pmw_1_2/doc/EntryField.html +++ /dev/null @@ -1,545 +0,0 @@ - - - - - - Pmw.EntryField reference manual - - - - -

Pmw.EntryField

- -
-
-

Name

-

Pmw.EntryField() - - entry widget with validation -

- - -
-

Inherits

-Pmw.MegaWidget
-
-

Description

-

- An entry field contains an entry widget with optional validation of - various kinds. Built-in validation may be used, such as - integer, real, time or date, or an external validation - function may be supplied. If valid text is entered, it will be - displayed with the normal background. If invalid text is entered, - it is not displayed and the previously displayed text is restored. - If partially valid text is entered, it will be displayed with a - background color to indicate it is in error. An example of - partially valid real text is '-.', which may be the first two - charactes of the valid string '-.5'. Some validators, such as - date, have a relaxed interpretation of partial validity, which - allows the user flexibility in how they enter the text.

- -

Validation is performed early, at each keystroke or other event - which modifies the text. However, if partially valid text is - permitted, the validity of the entered text can be checked just - before it is to be used, which is a form of late validation.

- -

Minimum and maximum values may be specified. Some validators also - accept other specifications, such as date and time formats and - separators.

- -

- - -
-

Validation function return values

-

- Validation is performed by a function which takes as its first - argument the entered text and returns one of three standard - values, indicating whether the text is valid:

- -
Pmw.OK
The text is valid.

- -
-
Pmw.ERROR
The text is invalid and is not acceptable for - display. In this case the entry will be restored to its - previous value.

- -
-
Pmw.PARTIAL
The text is partially valid and is acceptable - for display. In this case the text will be displayed - using the errorbackground color.

-

- - -
- -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
command -
-This specifies a function to call whenever the <Return> key is - pressed or invoke() is called. The default is None.

- - -
- -
errorbackground -
-Specifies the background color to use when displaying invalid or - partially valid text. The default is 'pink'.

- - -
- -
extravalidators -
-This is a dictionary of extra validators. The keys are the names - of validators which may be used in a future call to the - validate option. Each value in the dictionary is a tuple of - (validate_function, stringtovalue_function).

-

The validate_function is used to implement the validation and - the stringtovalue_function is used to convert the entry input - into a value which can be compared with the minimum and maximum - limits. These functions are as described for the validate - option.

- -

If either of these is not given as a function, it is assumed to be - the name of one of the other extra validators or one of the - standard validators. The alias search is performed when the - validate option is configured, not when the extravalidators - option is configured or when the validate function is called.

- -

If the name of one of the extra validators is the same as one of - the standard validators, the extra validator takes precedence. The default is {}.

- - - -
- -
invalidcommand -
-This is executed when invalid text is entered and the text is - restored to its previous value (that is, when the validate - function returns Pmw.ERROR). It is also called if an attempt is - made to set invalid text in a call to setentry(). The default - is self.bell.

- - -
- -
labelmargin -
-Initialisation option. If the labelpos option is not None, this specifies the - distance between the label component and the rest of the - megawidget. The default is 0.

- - -
- -
labelpos -
-Initialisation option. Specifies where to place the label component. If not - None, it should be a concatenation of one or two of the - letters 'n', 's', 'e' and 'w'. The first letter - specifies on which side of the megawidget to place the label. - If a second letter is specified, it indicates where on that - side to place the label. For example, if labelpos is 'w', - the label is placed in the center of the left hand side; if - it is 'wn', the label is placed at the top of the left - hand side; if it is 'ws', the label is placed at the - bottom of the left hand side.

-

If None, a label component is not created. The default is None.

- - - -
- -
modifiedcommand -
-This is called whenever the text of the entry has been changed - due to user action or by a call to setentry(). The default is None.

- - -
- -
sticky -
-Initialisation option. The default is 'ew'.

- - -
- -
validate -
-Specifies what kind of validation should be performed on the entry - input text.

-

The most general way to specify the validate option is as a - dictionary. The kind of validation is specified by the - 'validator' dictionary field, which may be the name of one of - the standard validators described below, the name of a validator - supplied by the extravalidators option, a function or None. - The default is None.

- -

Any other dictionary fields specify other restrictions on the - entered values. For all validators, the following fields may be - specified:

- -
'min'
Specifies the minimum acceptable value, or None if no - minimum checking should be performed. The default is None.

- -
-
'max'
Specifies the maximum acceptable value, or None if no - maximum checking should be performed. The default is None.

- -
-
'minstrict'
If true, then minimum checking is strictly enforced. - Otherwise, the entry input may be less than min, but will be - displayed using the errorbackground color. The default is true.

- -
-
'maxstrict'
If true, then maximum checking is strictly enforced. - Otherwise, the entry input may be more than max, but will be - displayed using the errorbackground color. The default is true.

- -
-

If the dictionary contains a 'stringtovalue' field, it overrides - the normal stringtovalue function for the validator. The - stringtovalue function is described below.

- -

Other fields in the dictionary (apart from the core fields - mentioned above) are passed on to the validator and - stringtovalue functions as keyword arguments.

- -

If validate is not a dictionary, then it is equivalent to - specifying it as a dictionary with a single 'validator' field. - For example, validate = 'real' is equivalent to /validate = - {'validator' : 'real'}/ and specifies real numbers without any - minimum or maximum limits and using '.' as the decimal point - character.

- -

The standard validators accepted in the 'validator' field are:

- -
'numeric'
An integer greater than or equal to 0. Digits - only. No sign.

- -
-
'integer'
Any integer (negative, 0 or positive) as accepted - by string.atol().

- -
-
'hexadecimal'
Hex number (with optional leading '0x'), as accepted - by string.atol(text, 16).

- -
-
'real'
A number, with or without a decimal point and optional - exponent (e or E), as accepted by string.atof(). This - validator accepts a 'separator' argument, which specifies - the character used to represent the decimal point. The - default 'separator' is '.'.

- -
-
'alphabetic'
Consisting of the letters 'a-z' and 'A-Z'. - In this case, 'min' and 'max' specify limits on the length - of the text.

- -
-
'alphanumeric'
Consisting of the letters 'a-z', 'A-Z' and '0-9'. - In this case, 'min' and 'max' specify limits on the length - of the text.

- -
-
'time'
Hours, minutes and seconds, in the format - 'HH:MM:SS', as accepted by Pmw.timestringtoseconds(). - This validator accepts a 'separator' argument, which - specifies the character used to separate the three fields. - The default separator is ':'. The time may be negative.

- -
-
'date'
Day, month and year, as accepted by - Pmw.datestringtojdn(). This validator accepts a - 'separator' argument, which specifies the character used to - separate the three fields. The default is ':'. This - validator also accepts a 'format' argument, which is passed to - Pmw.datestringtojdn() to specify the desired ordering of the - fields. The default is 'ymd'.

- -
-

If 'validator' is a function, then it will be called whenever - the contents of the entry may have changed due to user action or - by a call to setentry(). The function is called with at least - one argument, the first one being the new text as modified by the - user or setentry(). The other arguments are keyword arguments - made up of the non-core fields of the validate dictionary.

- -

The validator function should return Pmw.OK, Pmw.ERROR or - Pmw.PARTIAL as described above. It should not perform minimum - and maximum checking. This is done after the call, if it returns - Pmw.OK.

- -

The 'stringtovalue' field in the dictionary may be specified as - the name of one of the standard validators, the name of a - validator supplied by the extravalidators option, a function or - None.

- -

The stringtovalue function is used to convert the entry input - into a value which can then be compared with any minimum or - maximum values specified for the validator. If the 'min' or - 'max' fields are specified as strings, they are converted using - the stringtovalue function. The stringtovalue function is - called with the same arguments as the validator function. The - stringtovalue function for the standard number validators - convert the string to a number. Those for the standard alpha - validators return the length of the string. Those for the - standard 'time' and 'date' validators return the number of - seconds and the Julian Day Number, respectively. See - Pmw.stringtoreal(), Pmw.timestringtoseconds() and - Pmw.datestringtojdn().

- -

If the validator has been specified as a function and no - 'stringtovalue' field is given, then it defaults to the standard - python len() function.

- -

If 'validator' is None, no validation is performed. However, - minimum and maximum checking may be performed, according to the - stringtovalue function. For example, to limit the entry text to - a maximum of five characters:

- -
 Pmw.EntryField(validate = {'max' : 5})
- -

The validator functions for each of the standard validators can - be accessed as:

-
 Pmw.numericvalidator
- Pmw.integervalidator
- Pmw.hexadecimalvalidator
- Pmw.realvalidator
- Pmw.alphabeticvalidator
- Pmw.alphanumericvalidator
- Pmw.timevalidator
- Pmw.datevalidator
- - -

Whenever the validate option is configured, the text currently - displayed in the entry widget is revalidated. If it is not valid, - the errorbackground color is set and the invalidcommand - function is called. However, the displayed text is not modified.

- -

The default for validate is None.

- - - -
- -
value -
-Initialisation option. Specifies the initial contents of the entry. - If this text is invalid, it will be displayed with the - errorbackground color and the invalidcommand function will be called. - If both value and entry_textvariable options are specified in - the constructor, value will take precedence. The default is ''.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
entry -
-The widget where the user may enter text. Long text may be - scrolled horizontally by dragging with the middle mouse button. By default, this component is a Tkinter.Entry.

- - -
- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Frame.

- - -
- -
label -
-If the labelpos option is not None, this component is - created as a text label for the megawidget. See the - labelpos option for details. Note that to set, for example, - the text option of the label, you need to use the label_text - component option. By default, this component is a Tkinter.Label.

- - -
-
- -

Methods

-Only methods specific to this megawidget are described below. -For a description of its inherited methods, see the -manual for its base class -Pmw.MegaWidget. -In addition, methods from the -Tkinter.Entry class -are forwarded by this megawidget to the -entry component. -

- -
checkentry()
-Check the validity of the current contents of the entry widget - and return the result. - If the text is not valid, set the background to errorbackground and - call the invalidcommand function. If there is a variable - specified by the entry_textvariable option, this method should be - called after the set() method of the variable is called. If this - is not done in this case, the entry widget background will not be - set correctly.

- - -
- -
clear()
-Remove all text from the entry widget. Equivalent to setentry('').

- - -
- -
getvalue()
-Return the text displayed by the entry.

- - -
- -
invoke()
-Invoke the command specified by the command option as if the - <Return> key had been pressed and return the result.

- - -
- -
setentry(text)
-Same as setvalue() method.

- - -
- -
setvalue(text)
-Set the contents of the entry widget to text and carry out - validation as if the text had been entered by the user. If the - text is invalid, the entry widget will not be changed and the - invalidcommand function will be called. Return the validity - of text.

- - -
- -
valid()
-Return true if the contents of the entry widget are valid.

- - -
-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-        # Create and pack the EntryFields.
-        self._any = Pmw.EntryField(parent,
-                labelpos = 'w',
-                label_text = 'Any:',
-                validate = None,
-                command = self.execute)
-        self._real = Pmw.EntryField(parent,
-                labelpos = 'w',
-                value = '55.5',
-                label_text = 'Real (10.0 to 99.0):',
-                validate = {'validator' : 'real',
-                        'min' : 10, 'max' : 99, 'minstrict' : 0},
-                modifiedcommand = self.changed)
-        self._odd = Pmw.EntryField(parent,
-                labelpos = 'w',
-                label_text = 'Odd length:',
-                validate = self.custom_validate,
-                value = 'ABC')
-        self._date = Pmw.EntryField(parent,
-                labelpos = 'w',
-                label_text = 'Date (in 2000):',
-                value = '2000/2/29',
-                validate = {'validator' : 'date',
-                        'min' : '2000/1/1', 'max' : '2000/12/31',
-                        'minstrict' : 0, 'maxstrict' : 0,
-                        'format' : 'ymd'},
-                )
-        now = time.localtime(time.time())
-        self._date2 = Pmw.EntryField(parent,
-                labelpos = 'w',
-                label_text = 'Date (d.m.y):',
-                value = '%d.%d.%d' % (now[2], now[1], now[0]),
-                validate = {'validator' : 'date',
-                        'format' : 'dmy', 'separator' : '.'},
-                )
-        self._time = Pmw.EntryField(parent,
-                labelpos = 'w',
-                label_text = 'Time (24hr clock):',
-                value = '8:00:00',
-                validate = {'validator' : 'time',
-                        'min' : '00:00:00', 'max' : '23:59:59',
-                        'minstrict' : 0, 'maxstrict' : 0},
-                )
-        self._comma = Pmw.EntryField(parent,
-                labelpos = 'w',
-                label_text = 'Real (with comma):',
-                value = '123,456',
-                validate = {'validator' : 'real', 'separator' : ','},
-                )
-
-        entries = (self._any, self._real, self._odd, self._date, self._date2,
-                self._time, self._comma)
-
-        for entry in entries:
-            entry.pack(fill='x', expand=1, padx=10, pady=5)
-        Pmw.alignlabels(entries)
-
-        self._any.component('entry').focus_set()
-
-    def changed(self):
-        print 'Text changed, value is', self._real.getvalue()
-
-    def execute(self):
-        print 'Return pressed, value is', self._any.getvalue()
-
-    # This implements a custom validation routine.  It simply checks
-    # if the string is of odd length.
-    def custom_validate(self, text):
-        print 'text:', text
-        if len(text) % 2 == 0:
-          return -1
-        else:
-          return 1
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 22 May 1998 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/ExampleDemo.py b/Pmw/Pmw_1_2/doc/ExampleDemo.py deleted file mode 100644 index f7ec1e71..00000000 --- a/Pmw/Pmw_1_2/doc/ExampleDemo.py +++ /dev/null @@ -1,33 +0,0 @@ -title = 'Pmw.EXAMPLE demonstration' - -# Import Pmw from this directory tree. -import sys -sys.path[:0] = ['../../..'] - -import Tkinter -import Pmw - -class Demo: - def __init__(self, parent): - - # Create and pack the EXAMPLEs. - self.widget1 = Pmw.Counter(parent) - self.widget1.setentry('1') - self.widget1.pack() - - self.widget2 = Pmw.Counter(parent, increment = 10) - self.widget2.setentry('100') - self.widget2.pack() - -###################################################################### - -# Create demo in root window for testing. -if __name__ == '__main__': - root = Tkinter.Tk() - Pmw.initialise(root) - root.title(title) - - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) - exitButton.pack(side = 'bottom') - widget = Demo(root) - root.mainloop() diff --git a/Pmw/Pmw_1_2/doc/Group.gif b/Pmw/Pmw_1_2/doc/Group.gif deleted file mode 100644 index 9c4d8d5e..00000000 Binary files a/Pmw/Pmw_1_2/doc/Group.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/Group.html b/Pmw/Pmw_1_2/doc/Group.html deleted file mode 100644 index b961a1f2..00000000 --- a/Pmw/Pmw_1_2/doc/Group.html +++ /dev/null @@ -1,226 +0,0 @@ - - - - - - Pmw.Group reference manual - - - - -

Pmw.Group

- -
-
-

Name

-

Pmw.Group() - - frame with ring border and tag -

- - -
-

Inherits

-Pmw.MegaWidget
-
-

Description

-

- This megawidget consists of an interior frame with an exterior - ring border and an identifying tag displayed over the top edge of - the ring. The programmer can create other widgets within the - interior frame.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
collapsedsize -
-Initialisation option. The distance from the bottom of the tag to the bottom of the ring - when the groupchildsite is collapsed. The default is 6.

- - -
- -
tagindent -
-Initialisation option. The distance from the left edge of the ring to the left side of - the tag component. The default is 10.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
groupchildsite -
-The frame which can contain other widgets to be grouped. By default, this component is a Tkinter.Frame.

- - -
- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Frame.

- - -
- -
ring -
-This component acts as the enclosing ring around the - groupchildsite. The default borderwidth is 2 and the - default relief is 'groove'. By default, this component is a Tkinter.Frame.

- - -
- -
tag -
-The identifying tag displayed over the top edge of the enclosing - ring. If the pyclass for this component is None, (ie: - tag_pyclass = None, then no tag component is created. By default, this component is a Tkinter.Label.

- - -
-
- -

Methods

-Only methods specific to this megawidget are described below. -For a description of its inherited methods, see the -manual for its base class -Pmw.MegaWidget. -

- -
collapse()
-Do not display the groupchildsite component.

- - -
- -
expand()
-Display the groupchildsite component.

- - -
- -
interior()
-Return the frame within which the programmer may create widgets. - This is the same as component('groupchildsite').

- - -
- -
toggle()
-Display the groupchildsite component if it is currently hidden and - hide it if it is currently displayed.

- - -
-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-
-        # Create and pack the Groups.
-        w = Pmw.Group(parent, tag_text='label')
-        w.pack(fill = 'both', expand = 1, padx = 6, pady = 6)
-        cw = Tkinter.Label(w.interior(),
-                text = 'A group with the\ndefault Label tag')
-        cw.pack(padx = 2, pady = 2, expand='yes', fill='both')
-
-        w = Pmw.Group(parent, tag_pyclass = None)
-        w.pack(fill = 'both', expand = 1, padx = 6, pady = 6)
-        cw = Tkinter.Label(w.interior(), text = 'A group\nwithout a tag')
-        cw.pack(padx = 2, pady = 2, expand='yes', fill='both')
-
-        radiogroups = []
-        self.var = Tkinter.IntVar()
-        self.var.set(0)
-        radioframe = Tkinter.Frame(parent)
-        w = Pmw.Group(radioframe,
-                tag_pyclass = Tkinter.Radiobutton,
-                tag_text='radiobutton 1',
-                tag_value = 0,
-                tag_variable = self.var)
-        w.pack(fill = 'both', expand = 1, side='left')
-        cw = Tkinter.Frame(w.interior(),width=200,height=20)
-        cw.pack(padx = 2, pady = 2, expand='yes', fill='both')
-        radiogroups.append(w)
-
-        w = Pmw.Group(radioframe,
-                tag_pyclass = Tkinter.Radiobutton,
-                tag_text='radiobutton 2',
-                tag_font = Pmw.logicalfont('Helvetica', 4),
-                tag_value = 1,
-                tag_variable = self.var)
-        w.pack(fill = 'both', expand = 1, side='left')
-        cw = Tkinter.Frame(w.interior(),width=200,height=20)
-        cw.pack(padx = 2, pady = 2, expand='yes', fill='both')
-        radiogroups.append(w)
-        radioframe.pack(padx = 6, pady = 6, expand='yes', fill='both')
-        Pmw.aligngrouptags(radiogroups)
-
-        w = Pmw.Group(parent,
-                tag_pyclass = Tkinter.Checkbutton,
-                tag_text='checkbutton',
-                tag_foreground='blue')
-        w.pack(fill = 'both', expand = 1, padx = 6, pady = 6)
-        cw = Tkinter.Frame(w.interior(),width=150,height=20)
-        cw.pack(padx = 2, pady = 2, expand='yes', fill='both')
-
-        w = Pmw.Group(parent,
-                tag_pyclass = Tkinter.Button,
-                tag_text='Tkinter.Button')
-        w.configure(tag_command = w.toggle)
-        w.pack(fill = 'both', expand = 1, padx = 6, pady = 6)
-        cw = Tkinter.Label(w.interior(),
-                background = 'aliceblue',
-                text = 'A group with\na Button tag!?'
-        )
-        cw.pack(padx = 2, pady = 2, expand='yes', fill='both')
-
-        w = Pmw.Group(parent,
-                tag_pyclass = Tkinter.Button,
-                tag_text='Show/Hide')
-        w.configure(tag_command = w.toggle)
-        w.pack(fill = 'both', expand = 1, padx = 6, pady = 6)
-        cw = Tkinter.Label(w.interior(),
-                background = 'aliceblue',
-                text = 'Now you see me.\nNow you don\'t.'
-        )
-        cw.pack(padx = 2, pady = 2, expand='yes', fill='both')
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 15 November 1998 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/HistoryText.gif b/Pmw/Pmw_1_2/doc/HistoryText.gif deleted file mode 100644 index 5ee3ae37..00000000 Binary files a/Pmw/Pmw_1_2/doc/HistoryText.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/HistoryText.html b/Pmw/Pmw_1_2/doc/HistoryText.html deleted file mode 100644 index c42dad64..00000000 --- a/Pmw/Pmw_1_2/doc/HistoryText.html +++ /dev/null @@ -1,427 +0,0 @@ - - - - - - Pmw.HistoryText reference manual - - - - -

Pmw.HistoryText

- -
-
-

Name

-

Pmw.HistoryText() - - text widget with a course-grained form of history -

- - -
-

Inherits

-Pmw.ScrolledText
-
-

Description

-

- A history text is a scrolled text widget with added functionality - to maintain a history of each screen and allow editing of prior - screens. Here, screen refers to the entire contents of the text - widget. This widget does not support a fine-grained history of - every change made to the text.

- -

Together with a few buttons and a scrolled text to display the - results, a history text can be used as the query-entry part of a - simple interactive text-based database query system. When the - user enters and executes a query, the query (the entire contents - of the text widget) is added to the history list. The user may - view previous queries and either execute them again or modify them - and execute the new query. If a previously executed query is - modified, the user may undo or redo all changes made to the query - before the query is executed.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
borderframe -
-Initialisation option. If true, the borderframe component will be created. The default is 0.

- - -
- -
columnheader -
-Initialisation option. If true, the columnheader component will be created. The default is 0.

- - -
- -
compressany -
-See addhistory(). The default is 1.

- - -
- -
compresstail -
-See addhistory(). The default is 1.

- - -
- -
historycommand -
-This is a callback to indicate whether the currently displayed - entry in the history list has a previous or next entry. The - callback is given two arguments, prevstate and nextstate. If - the currently displayed entry is first in the history list, then - prevstate is 'disabled', otherwise it is 'normal'. If the - currently displayed entry is last in the history list, then - nextstate is 'disabled', otherwise it is 'normal'. These - values can be used, for example, to modify the state of Next and - Previous buttons that call the next() and prev() methods. The default is None.

- - -
- -
hscrollmode -
-The horizontal scroll mode. If 'none', the horizontal scrollbar - will never be displayed. If 'static', the scrollbar will always - be displayed. If 'dynamic', the scrollbar will be displayed - only if necessary. The default is 'dynamic'.

- - -
- -
labelmargin -
-Initialisation option. If the labelpos option is not None, this specifies the - distance between the label component and the rest of the - megawidget. The default is 0.

- - -
- -
labelpos -
-Initialisation option. Specifies where to place the label component. If not - None, it should be a concatenation of one or two of the - letters 'n', 's', 'e' and 'w'. The first letter - specifies on which side of the megawidget to place the label. - If a second letter is specified, it indicates where on that - side to place the label. For example, if labelpos is 'w', - the label is placed in the center of the left hand side; if - it is 'wn', the label is placed at the top of the left - hand side; if it is 'ws', the label is placed at the - bottom of the left hand side.

-

If None, a label component is not created. The default is None.

- - - -
- -
rowcolumnheader -
-Initialisation option. If true, the rowcolumnheader component will be created. The default is 0.

- - -
- -
rowheader -
-Initialisation option. If true, the rowheader component will be created. The default is 0.

- - -
- -
scrollmargin -
-Initialisation option. The distance between the scrollbars and the text widget. The default is 2.

- - -
- -
usehullsize -
-Initialisation option. If true, the size of the megawidget is determined solely by the - width and height options of the hull component.

-

Otherwise, the size of the megawidget is determined by the width - and height of the text component, along with the size and/or - existence of the other components, such as the label, the - scrollbars and the scrollmargin option. All these affect the - overall size of the megawidget. The default is 0.

- - - -
- -
vscrollmode -
-The vertical scroll mode. If 'none', the vertical scrollbar - will never be displayed. If 'static', the scrollbar will always - be displayed. If 'dynamic', the scrollbar will be displayed - only if necessary. The default is 'dynamic'.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
borderframe -
-A frame widget which snuggly fits around the text widget, to give - the appearance of a text border. It is created with a border so - that the text widget, which is created without a border, looks - like it has a border. By default, this component is a Tkinter.Frame.

- - -
- -
columnheader -
-A text widget with a default height of 1 displayed above the main - text widget and which scrolls horizontally in sync with the - horizontal scrolling of the main text widget. By default, this component is a Tkinter.Text. Its component group is Header.

- - -
- -
horizscrollbar -
-The horizontal scrollbar. By default, this component is a Tkinter.Scrollbar. Its component group is Scrollbar.

- - -
- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Frame.

- - -
- -
label -
-If the labelpos option is not None, this component is - created as a text label for the megawidget. See the - labelpos option for details. Note that to set, for example, - the text option of the label, you need to use the label_text - component option. By default, this component is a Tkinter.Label.

- - -
- -
rowcolumnheader -
-A text widget displayed to the top left of the main text widget, - above the row header and to the left of the column header if they - exist. The widget is not scrolled automatically. By default, this component is a Tkinter.Text. Its component group is Header.

- - -
- -
rowheader -
-A text widget displayed to the left of the main text widget and - which scrolls vertically in sync with the vertical scrolling of - the main text widget. By default, this component is a Tkinter.Text. Its component group is Header.

- - -
- -
text -
-The text widget which is scrolled by the scrollbars. If the - borderframe option is true, this is created with a borderwidth - of 0 to overcome a known problem with text widgets: if a widget - inside a text widget extends across one of the edges of the text - widget, then the widget obscures the border of the text widget. - Therefore, if the text widget has no border, then this overlapping - does not occur. By default, this component is a Tkinter.Text.

- - -
- -
vertscrollbar -
-The vertical scrollbar. By default, this component is a Tkinter.Scrollbar. Its component group is Scrollbar.

- - -
-
- -

Methods

-Only methods specific to this megawidget are described below. -For a description of its inherited methods, see the -manual for its base class -Pmw.ScrolledText. -

- -
addhistory()
-Append the currently displayed text to the history list.

-

If compressany is true, a new entry will be added to the history - list only if the currently displayed entry has changed.

- -

If compresstail is true, a new entry will be added to the - history list only if the currently displayed entry has changed - or if it is not the last entry in the history list.

- - - -
- -
gethistory()
-Return the history list. Each entry in the list is a 3-tuple. - The first item in a history entry is the original text as added by - addhistory(). The second item is the edited text (if the user - has modified the entry but addhistory() has not yet been called - on the text). The third item specifies whether the entry should - currently display the original or modified text.

- - -
- -
next()
-Display the next screen in the history list.

- - -
- -
prev()
-Display the previous screen in the history list.

- - -
- -
redo()
-Reverse the effect of undo().

- - -
- -
undo()
-Undo all changes made since this entry was added to the history - list.

- - -
-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-        # Create and pack the PanedWidget to hold the query and result
-        # windows.
-        # !! panedwidget should automatically size to requested size
-        panedWidget = Pmw.PanedWidget(parent,
-                orient = 'vertical',
-                hull_height = 400,
-                hull_width = 550)
-        panedWidget.add('query', min = 0.05, size = 0.2)
-        panedWidget.add('buttons', min = 0.1, max = 0.1)
-        panedWidget.add('results', min = 0.05)
-        panedWidget.pack(fill = 'both', expand = 1)
-
-        # Create and pack the HistoryText.
-        self.historyText = Pmw.HistoryText(panedWidget.pane('query'),
-                text_wrap = 'none',
-                text_width = 60,
-                text_height = 10,
-                historycommand = self.statechange,
-        )
-        self.historyText.pack(fill = 'both', expand = 1)
-        self.historyText.component('text').focus()
-
-        buttonList = (
-            [20, None],
-            ['Clear', self.clear],
-            ['Undo', self.historyText.undo],
-            ['Redo', self.historyText.redo],
-            [20, None],
-            ['Prev', self.historyText.prev],
-            ['Next', self.historyText.next],
-            [30, None],
-            ['Execute', Pmw.busycallback(self.executeQuery)],
-        )
-        self.buttonDict = {}
-
-        buttonFrame = panedWidget.pane('buttons')
-        for text, cmd in buttonList:
-            if type(text) == type(69):
-                frame = Tkinter.Frame(buttonFrame, width = text)
-                frame.pack(side = 'left')
-            else:
-                button = Tkinter.Button(buttonFrame, text = text, command = cmd)
-                button.pack(side = 'left')
-                self.buttonDict[text] = button
-
-        for text in ('Prev', 'Next'):
-            self.buttonDict[text].configure(state = 'disabled')
-
-        self.results = Pmw.ScrolledText(panedWidget.pane('results'), text_wrap = 'none')
-        self.results.pack(fill = 'both', expand = 1)
-
-    def statechange(self, prevstate, nextstate):
-        self.buttonDict['Prev'].configure(state = prevstate)
-        self.buttonDict['Next'].configure(state = nextstate)
-
-    def clear(self):
-        self.historyText.delete('1.0', 'end')
-
-    def addnewlines(self, text):
-        if len(text) == 1:
-            text = text + '\n'
-        if text[-1] != '\n':
-            text = text + '\n'
-        if text[-2] != '\n':
-            text = text + '\n'
-        return text
-
-    def executeQuery(self):
-        sql = self.historyText.get()
-        self.results.insert('end', 'Query:\n' + self.addnewlines(sql))
-        self.results.see('end')
-        self.results.update_idletasks()
-        self.historyText.addhistory()
-        results = 'Results:\nfoo'
-        if len(results) > 0:
-            self.results.insert('end', self.addnewlines(results))
-        self.results.see('end')
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 20 May 2002 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/LabeledWidget.gif b/Pmw/Pmw_1_2/doc/LabeledWidget.gif deleted file mode 100644 index dfa61540..00000000 Binary files a/Pmw/Pmw_1_2/doc/LabeledWidget.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/LabeledWidget.html b/Pmw/Pmw_1_2/doc/LabeledWidget.html deleted file mode 100644 index 726ba08f..00000000 --- a/Pmw/Pmw_1_2/doc/LabeledWidget.html +++ /dev/null @@ -1,170 +0,0 @@ - - - - - - Pmw.LabeledWidget reference manual - - - - -

Pmw.LabeledWidget

- -
-
-

Name

-

Pmw.LabeledWidget() - - frame with label -

- - -
-

Inherits

-Pmw.MegaWidget
-
-

Description

-

- This megawidget consists of an interior frame with an associated - label which can be positioned on any side of the frame. The - programmer can create other widgets within the interior frame.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
labelmargin -
-Initialisation option. If the labelpos option is not None, this specifies the - distance between the label component and the rest of the - megawidget. The default is 0.

- - -
- -
labelpos -
-Initialisation option. Specifies where to place the label component. If not - None, it should be a concatenation of one or two of the - letters 'n', 's', 'e' and 'w'. The first letter - specifies on which side of the megawidget to place the label. - If a second letter is specified, it indicates where on that - side to place the label. For example, if labelpos is 'w', - the label is placed in the center of the left hand side; if - it is 'wn', the label is placed at the top of the left - hand side; if it is 'ws', the label is placed at the - bottom of the left hand side.

-

If None, a label component is not created. The default is None.

- - - -
- -
sticky -
-Initialisation option. The default is 'nsew'.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Frame.

- - -
- -
label -
-If the labelpos option is not None, this component is - created as a text label for the megawidget. See the - labelpos option for details. Note that to set, for example, - the text option of the label, you need to use the label_text - component option. By default, this component is a Tkinter.Label.

- - -
- -
labelchildsite -
-The frame which can contain other widgets to be labelled. By default, this component is a Tkinter.Frame.

- - -
-
- -

Methods

-Only methods specific to this megawidget are described below. -For a description of its inherited methods, see the -manual for its base class -Pmw.MegaWidget. -

- -
interior()
-Return the frame within which the programmer may create widgets. - This is the same as component('labelchildsite').

- - -
-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-
-        # Create a frame to put the LabeledWidgets into
-        frame = Tkinter.Frame(parent, background = 'grey90')
-        frame.pack(fill = 'both', expand = 1)
-
-        # Create and pack the LabeledWidgets.
-        column = 0
-        row = 0
-        for pos in ('n', 'nw', 'wn', 'w'):
-            lw = Pmw.LabeledWidget(frame,
-                    labelpos = pos,
-                    label_text = pos + ' label')
-            lw.component('hull').configure(relief='sunken', borderwidth=2)
-            lw.grid(column=column, row=row, padx=10, pady=10)
-            cw = Tkinter.Button(lw.interior(), text='child\nsite')
-            cw.pack(padx=10, pady=10, expand='yes', fill='both')
-
-            # Get ready for next grid position.
-            column = column + 1
-            if column == 2:
-              column = 0
-              row = row + 1
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 8 November 1998 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/MainMenuBar.gif b/Pmw/Pmw_1_2/doc/MainMenuBar.gif deleted file mode 100644 index aa7a7bf8..00000000 Binary files a/Pmw/Pmw_1_2/doc/MainMenuBar.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/MainMenuBar.html b/Pmw/Pmw_1_2/doc/MainMenuBar.html deleted file mode 100644 index 4f0fea88..00000000 --- a/Pmw/Pmw_1_2/doc/MainMenuBar.html +++ /dev/null @@ -1,421 +0,0 @@ - - - - - - Pmw.MainMenuBar reference manual - - - - -

Pmw.MainMenuBar

- -
-
-

Name

-

Pmw.MainMenuBar() - - manager for toplevel native menus -

- - -
-

Inherits

-Pmw.MegaArchetype
-
-

Description

-

- This class is a wrapper for the Tkinter.Menu class. It should be - used as the main menu of toplevel windows. The class is similar - to Pmw.MenuBar, but should be used when native menus are required. - See the Tkinter.Menu documentation for full details.

- -

This class should be created as the child of a Tkinter.Toplevel - and should then be specified as the menu associated with the - toplevel, using the toplevel's configure() method. For example:

-
 # Create a Pmw.MegaToplevel.
- megaToplevel = Pmw.MegaToplevel()
- # Get the Tkinter.Toplevel from Pmw.MegaToplevel.
- toplevel = megaToplevel.interior()
- # Create the menu bar for the toplevel.
- menuBar = Pmw.MainMenuBar(toplevel)
- # Configure the toplevel to use the menuBar.
- toplevel.configure(menu = menuBar)
- - -

There are methods to add menus, both as toplevel menus and - sub-menus, and for adding menu items to the menus. Each menu item - may have help text to be displayed by a Pmw.Balloon. Each menu and - cascaded menu (sub-menu) is referenced by name which is supplied - on creation.

- -

This megawidget is derived from Pmw.MegaArchetype (not Pmw.MegaWidget - like most other megawidgets), with the hull class being - Tkinter.Menu.

- -

(Note that due to bugs in Tk's menubar functionality, balloon help - has not been implemented and status help does not work properly.)

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
balloon -
-Specifies a Pmw.Balloon to display the help text for menu items. If - None, no help is displayed. If the balloon has an associated - Pmw.MessageBar, the help text will also be displayed there.

-

Due to a bug in some versions of Tk (8.0 and possible others), - help text will not be displayed by the balloon. However, help - text will be displayed in the balloon's associated messagebar. The default is None.

- - - -
- -
hotkeys -
-Initialisation option. If true, keyboard accelerators will be assigned to each menu item. - Keyboard accelerators can be used to access the menus without - using the mouse. The accelerator character is always one of the - alphanumeric characters in the text label of the menu item and is - indicated by an underline.

-

To select a menu, simultaneously press the <Alt> key and the - accelerator character indicated on a toplevel menu item. The - arrows keys can then be used to select other menus and menu items. - To invoke a menu item, press <Return> or press the accelerator - character indicated on the menu item.

- -

Each accelerator character will be assigned automatically unless - traverseSpec is supplied to the addmenu(), addmenuitem() or - addcascademenu() methods. The automatically selected - accelerator character for a menu item is the first character in - the label text that has not already been used as an accelerator in - the menu containing the menu item.

- -

If traverseSpec is given, it must be either an integer or a - character. If an integer, it specifies the index of the character - in the label text to use as the accelerator character. If a - character, it specifies the character to use as the accelerator - character. The default is 1.

- - - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
hull -
-The toplevel menu widget. By default, this component is a Tkinter.Menu.

- - -
-
-

Dynamic components

-

- Menu components are created dynamically by the addmenu() and - addcascademenu() methods. By default, these are of type - Tkinter.Menu and are created with a component group of Menu.

-

- - - -
- -

Methods

-Only methods specific to this megawidget are described below. -For a description of its inherited methods, see the -manual for its base class -Pmw.MegaArchetype. -In addition, methods from the -Tkinter.Menu class -are forwarded by this megawidget to the -hull component. -

- -
addcascademenu(parentMenuName, menuName, statusHelp = '', traverseSpec = None, **kw)
-Add a cascade menu (sub-menu) to the menu parentMenuName. The - menuName argument must not be the same as any menu already - created using the addmenu() or addcascademenu() methods.

-

A menu item in the parent menu is created (with the - add_cascade() method of the parent menu) using all keyword - arguments except tearoff and name.

- -

If the label keyword argument is not given, the label option - of the menu item defaults to menuName. If the underline - keyword argument is not given (and the hotkeys megawidget option - is true) the underline option is determined as described under - hotkeys and is used to specify the keyboard accelerator.

- -

The statusHelp argument is used as the help string for the menu - item. This is displayed using the showstatus() method of the - balloon.

- -

The tearoff and name keyword arguments, if present, are passed - to the constructor of the menu. See Tkinter.Menu for details of - these options. The menu is created as a component named - menuName.

- - - -
- -
addmenu(menuName, balloonHelp, statusHelp = None, traverseSpec = None, **kw)
-Add a cascade menu to the toplevel menu. The menuName argument - must not be the same as any menu already created using the - addmenu() or addcascademenu() methods.

-

A menu item in the toplevel menu is created (with the - add_cascade() method) using all keyword arguments except - tearoff and name.

- -

If the label keyword argument is not given, the label option - of the menu button defaults to menuName. If the underline - keyword argument is not given (and the hotkeys megawidget option - is true) the underline option is determined as described under - hotkeys and is used to specify the keyboard accelerator.

- -

The statusHelp argument is used as the help string for the menu - item. This is displayed using the showstatus() method of the - balloon. Currently balloonHelp is not used, due to a bug in Tk - version 8.0.

- -

The tearoff and name keyword arguments, if present, are passed - to the constructor of the menu. See Tkinter.Menu for details of - these options. The menu is created as a component named - menuName.

- - - -
- -
addmenuitem(menuName, itemType, statusHelp = '', traverseSpec = None, **kw)
-Add a menu item to the menu menuName. The kind of menu item is - given by itemType and may be one of command, separator, - checkbutton, radiobutton or cascade (although cascade menus - are better added using the addcascademenu() method). Any - keyword arguments present will be passed to the menu when creating - the menu item. See Tkinter.Menu for the valid options for each - item type. In addition, a keyboard accelerator may be - automatically given to the item, as described under hotkeys.

-

When the mouse is moved over the menu item, the helpString will - be displayed by the balloon's statuscommand.

- - - -
- -
deletemenu(menuName)
-Delete the menu menuName and all its items. The menu may either - be a toplevel menu or a cascade menu.

- - -
- -
deletemenuitems(menuName, start, end = None)
-Delete menu items from the menu menuName. If end is not - given, the start item is deleted. Otherwise all items from - start to end are deleted.

- - -
- -
disableall()
-Disable all toplevel menus.

- - -
- -
enableall()
-Enable all toplevel menus.

- - -
-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-        # Create button to launch the toplevel with main menubar.
-        w = Tkinter.Button(parent, text = 'Show Pmw.MainMenuBar demo',
-                command = lambda parent=parent: MainMenuBarToplevel(parent))
-        w.pack(padx = 8, pady = 8)
-
-class MainMenuBarToplevel:
-    def __init__(self, parent):
-        # Create the toplevel to contain the main menubar.
-        megaToplevel = Pmw.MegaToplevel(parent, title = title)
-        toplevel = megaToplevel.interior()
-
-        # Create the Balloon for this toplevel.
-        self.balloon = Pmw.Balloon(toplevel)
-
-        # Create and install the MenuBar.
-        menuBar = Pmw.MainMenuBar(toplevel,
-                balloon = self.balloon)
-        toplevel.configure(menu = menuBar)
-        self.menuBar = menuBar
-
-        # Add some buttons to the MainMenuBar.
-        menuBar.addmenu('File', 'Close this window or exit')
-        menuBar.addmenuitem('File', 'command', 'Close this window',
-                command = PrintOne('Action: close'),
-                label = 'Close')
-        menuBar.addmenuitem('File', 'separator')
-        menuBar.addmenuitem('File', 'command', 'Exit the application',
-                command = PrintOne('Action: exit'),
-                label = 'Exit')
-
-        menuBar.addmenu('Edit', 'Cut, copy or paste')
-        menuBar.addmenuitem('Edit', 'command', 'Delete the current selection',
-                command = PrintOne('Action: delete'),
-                label = 'Delete')
-
-        menuBar.addmenu('Options', 'Set user preferences')
-        menuBar.addmenuitem('Options', 'command', 'Set general preferences',
-                command = PrintOne('Action: general options'),
-                label = 'General...')
-
-        # Create a checkbutton menu item.
-        self.toggleVar = Tkinter.IntVar()
-        # Initialise the checkbutton to 1:
-        self.toggleVar.set(1)
-        menuBar.addmenuitem('Options', 'checkbutton', 'Toggle me on/off',
-                label = 'Toggle',
-                command = self._toggleMe,
-                variable = self.toggleVar)
-        self._toggleMe()
-
-        menuBar.addcascademenu('Options', 'Size',
-                'Set some other preferences', traverseSpec = 'z', tearoff = 1)
-        for size in ('tiny', 'small', 'average', 'big', 'huge'):
-            menuBar.addmenuitem('Size', 'command', 'Set size to ' + size,
-                    command = PrintOne('Action: size ' + size),
-                    label = size)
-
-        menuBar.addmenu('Help', 'User manuals', name = 'help')
-        menuBar.addmenuitem('Help', 'command', 'About this application',
-                command = PrintOne('Action: about'),
-                label = 'About...')
-
-        # Create and pack the main part of the window.
-        self.mainPart = Tkinter.Label(toplevel,
-                text = 'This is the\nmain part of\nthe window',
-                background = 'black',
-                foreground = 'white',
-                padx = 30,
-                pady = 30)
-        self.mainPart.pack(fill = 'both', expand = 1)
-
-        # Create and pack the MessageBar.
-        self.messageBar = Pmw.MessageBar(toplevel,
-                entry_width = 40,
-                entry_relief='groove',
-                labelpos = 'w',
-                label_text = 'Status:')
-        self.messageBar.pack(fill = 'x', padx = 10, pady = 10)
-        self.messageBar.message('state',
-            'Balloon/status help not working properly - Tk menubar bug')
-
-        buttonBox = Pmw.ButtonBox(toplevel)
-        buttonBox.pack(fill = 'x')
-        buttonBox.add('Disable\nall', command = menuBar.disableall)
-        buttonBox.add('Enable\nall', command = menuBar.enableall)
-        buttonBox.add('Create\nmenu', command = self.add)
-        buttonBox.add('Delete\nmenu', command = self.delete)
-        buttonBox.add('Create\nitem', command = self.additem)
-        buttonBox.add('Delete\nitem', command = self.deleteitem)
-
-        # Configure the balloon to displays its status messages in the
-        # message bar.
-        self.balloon.configure(statuscommand = self.messageBar.helpmessage)
-
-        self.testMenuList = []
-
-    def _toggleMe(self):
-        print 'Toggle value:', self.toggleVar.get()
-
-    def add(self):
-        if len(self.testMenuList) == 0:
-            num = 0
-        else:
-            num = self.testMenuList[-1]
-        num = num + 1
-        name = 'Menu%d' % num
-        self.testMenuList.append(num)
-
-        self.menuBar.addmenu(name, 'This is ' + name)
-
-    def delete(self):
-        if len(self.testMenuList) == 0:
-            self.menuBar.bell()
-        else:
-            num = self.testMenuList[0]
-            name = 'Menu%d' % num
-            del self.testMenuList[0]
-            self.menuBar.deletemenu(name)
-
-    def additem(self):
-        if len(self.testMenuList) == 0:
-            self.menuBar.bell()
-        else:
-            num = self.testMenuList[-1]
-            menuName = 'Menu%d' % num
-            menu = self.menuBar.component(menuName)
-            if menu.index('end') is None:
-                label = 'item X'
-            else:
-                label = menu.entrycget('end', 'label') + 'X'
-            self.menuBar.addmenuitem(menuName, 'command', 'Help for ' + label,
-                    command = PrintOne('Action: ' + menuName + ': ' + label),
-                    label = label)
-            
-    def deleteitem(self):
-        if len(self.testMenuList) == 0:
-            self.menuBar.bell()
-        else:
-            num = self.testMenuList[-1]
-            menuName = 'Menu%d' % num
-            menu = self.menuBar.component(menuName)
-            if menu.index('end') is None:
-                self.menuBar.bell()
-            else:
-                self.menuBar.deletemenuitems(menuName, 0)
-            
-class PrintOne:
-    def __init__(self, text):
-        self.text = text
-
-    def __call__(self):
-        print self.text
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 22 April 2000 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/MegaArchetype.html b/Pmw/Pmw_1_2/doc/MegaArchetype.html deleted file mode 100644 index 03f62660..00000000 --- a/Pmw/Pmw_1_2/doc/MegaArchetype.html +++ /dev/null @@ -1,459 +0,0 @@ - - - - - - Pmw.MegaArchetype reference manual - - - - -

Pmw.MegaArchetype

- -
-

Name

-

Pmw.MegaArchetype() - - abstract base class for all Pmw megawidgets -

- - -
-

Description

-

- This class is the basis for all Pmw megawidgets. It provides - methods to manage options and component widgets.

- -

This class is normally used as a base class for other classes. If - the hullClass argument is specified, such as in the Pmw.MegaWidget - and Pmw.MegaToplevel classes, a container widget is created to act - as the parent of all other component widgets. Classes derived - from these sub classes create other component widgets and options - to implement megawidgets that can be used in applications.

- -

If no hullClass argument is given to the constructor, no - container widget is created and only the option configuration - functionality is available.

- -

- - -
-

Components

-

- A megawidget is generally made up of other widgets packed - within the megawidget's containing widget. These sub-widgets - are called the components of the megawidget and are given - logical names for easy reference. The component mechanism - allows the user of a megawidget to gain controlled access to - some of the internals of the megawidget, for example to call a - method of a component or to set a component's configuration - options.

- -

Sub components: If a component is itself a megawidget containing - sub-components, then these sub-components can be referred to - using the notation component_subcomponent. For example, - Pmw.ComboBox has a component named entryfield which is an - instance of Pmw.EntryField, which itself has a Tkinter.Entry - component named entry. In the context of the combobox, this - entry widget can be referred to as entryfield_entry.

- -

Component aliases: Because the sub-component notation may - make component names inconveniently long, components and - sub-components can be aliased to simpler names. For example, - the entryfield_entry sub-component of Pmw.ComboBox is aliased - to simply entry. If there is no conflict in component - names, sub-component names are usually aliased to the name of - the "leaf" component.

- -

Component groups: Similar components of a megawidget can be - given a group name, which allows all components of a group - to be referenced using the one group name. For example, the - two arrow components of Pmw.Counter have a group name of Arrow. - Also, megawidgets that can create an unlimited number of - similar components, such as Pmw.ButtonBox, create each of these - components with the same group name. By convention, group - names begin with a capital letter.

-

- - - -
-

Options

-

- A megawidget defines options which allow the megawidget user - to modify the appearance and behaviour of the megawidget. - Using the same technique as Tkinter widgets, the values of - megawidget options may be set in calls to the constructor and - to configure() and the values may be queried by calls to - cget() and configure(). Like Tkinter widgets, megawidget - options are initialised with default values. Also, if the - useTkOptionDb option to Pmw.initialise() has been set, - then the Tk option database will be queried to get the initial - values. Strings found in the option database are converted - to python objects (integer, float, tuple, dictionary, etc) - using a restricted eval() call. Anything that is not accepted by - eval() is treated as a string.

- -

Inherited options: As well as the options defined in a class, - a derived class inherits all options of its base classes. The - default value of an option defined by a base class may be - modified by the derived class.

- -

Initialisation options: Some megawidget options can only be - set in the call to the constructor. These are called - initialisation options. Unlike normal configuration - options, they cannot be set by calling the configure() - method.

- -

Component options: Options of the components of a megawidget - can be referred to using the notation component_option. - Like the megawidget options, component options can be used in - calls to the constructor and to the cget() and configure() - methods. For example, the state option of the Tkinter.Text - text component of Pmw.ScrolledText may be set by calling

-
 widget.configure(text_state = 'disabled')
- - -

Sub-components, component aliases and component groups may - also be combined with options. For example, the state - option of the entryfield_entry component of Pmw.ComboBox - may be set by calling

-
 combobox.configure(entryfield_entry_state = 'normal')
- - -

Since it has an alias, it is more convenient to use the - equivalent form

-
 combobox.configure(entry_state = 'normal')
- - -

Also, the background color of both arrows of Pmw.Counter - can be set using the Arrow component group.

-
 counter.configure(Arrow_background = 'aliceblue')
- - -

- - -
-

The pyclass component option

-

- The pyclass component option is a special notation that can - be used to specify a non-default python class for a component. - This can only be used when the component is being constructed. - For a component created during the construction of its parent - megawidget, this option must be given to the constructor in - the form component_pyclass. For example, to change the - python class of the text sub-component of Pmw.TextDialog - to a class FontText.Text

-
 dialog = Pmw.TextDialog(text_pyclass = FontText.Text)
- - -

For components created after the construction of the parent - megawidget, the pyclass option must be passed into the - method which constructs the component. For example, to set - the python class of a button in Pmw.ButtonBox to a class - MyButton:

-
 buttonBox.add('special', pyclass = MyButton)
- - -

The new python class of the component must support all methods - and options that are used by the megawidget when operating on - the component. The exact interface required for each - component is not documented. You will have to examine the Pmw - source code. However, any class derived from the default - class of a component can be used as the new class of the - component, as long as all of the original methods and options - are still supported. For example, any class derived from - Tkinter.Text can be used as the class of the text - sub-component of Pmw.TextDialog.

- -

The pyclass component option should not be confused with the - class option that some of the Tk widgets support. The - class option sets the Tk option database class for the - widget and is used by Tk to query the database for the default - values of the widget's other options. The name pyclass was - chosen so that it did not conflict with any known Tk options.

- -

- - -
-

Construction

-

- The constructors of classes derived from this class all accept - the same arguments: one positional argument and any number of - keyword arguments. The positional argument defaults to None - (meaning the root window) and specifies the widget to use as - the parent when creating the - megawidget's hull component. The keyword arguments define - initial values for options. The format for the constructors - of derived classes is:

- -
   def __init__(self, parent = None, **kw):
-

- - - -
- -

Methods

- -
addoptions(optionDefs)
-Add additional options for this megawidget. The optionDefs - argument is treated in the same way as for the defineoptions() - method.

-

This method is for use by derived classes. It is only used if a - megawidget should conditionally define some options, perhaps - depending on the value of other options. Usually, megawidgets - unconditionally define all their options in the call to - defineoptions() and do not need to use addoptions(). This - method must be called after the call to defineoptions() and - before the call to initialiseoptions().

- - - -
- -
cget(option)
-Return the current value of option (which should be in the - format described in the Options section). This method is also - available using object subscripting, for example - myWidget['font']. Unlike Tkinter's cget(), which always returns - a string, this method returns the same value and type as used when - the option was set (except where option is a component option - and the component is a Tkinter widget, in which case it returns - the string returned by Tcl/Tk).

- - -
- -
component(name)
-Return the component widget whose name is name. This - allows the user of a megawidget to access and configure component - widgets directly.

- - -
- -
componentaliases()
-Return the list of aliases for components. Each item in the list - is a tuple whose first item is the name of the alias and whose - second item is the name of the component or sub-component it - refers to.

- - -
- -
componentgroup(name)
-Return the group of the component whose name is name or None - if it does not have a group.

- - -
- -
components()
-Return a sorted list of names of the components of this - megawidget.

- - -
- -
configure(option = None, **kw)
-Query or configure the megawidget options.

-

If no arguments are given, return a tuple consisting of all - megawidget options and values, each as a 5-element tuple - (name, resourceName, resourceClass, default, value). - This is in the same format as the value returned by the standard - Tkinter configure() method, except that the resource name is - always the same as the option name and the resource class is the - option name with the first letter capitalised.

- -

If one argument is given, return the 5 element tuple for option.

- -

Otherwise, set the configuration options specified by the keyword - arguments. Each key should be in the format described in the - Options section.

- - - -
- -
createcomponent(componentName, componentAliases, componentGroup, widgetClass, *widgetArgs, **kw)
-Create a component widget by calling widgetClass with the - arguments given by widgetArgs and any keyword arguments. The - componentName argument is the name by which the component will - be known and must not contain the underscore, '_', character. - The componentGroup argument specifies the group of the - component. The componentAliases argument is a sequence of - 2-element tuples, whose first item is an alias name and whose - second item is the name of the component or sub-component it is to - refer to.

-

If this method is called during megawidget construction, any - component options supplied to the megawidget constructor which - refer to this component (by componentName or componentGroup) - are added to the kw dictionary before calling widgetClass. If - the dictionary contains a 'pyclass' key, then this item is - removed from the dictionary and the value is used instead of - widgetClass. For more details see The pyclass component option - section.

- -

This method may be called by derived classes during or after - megawidget construction. It returns the instance of the class - created.

- - - -
- -
createlabel(parent, childCols = 1, childRows = 1)
-Create a Tkinter.Label component named 'label' in the parent - widget. This is a convenience method used by several megawidgets - that require an optional label. The widget must have options - named labelpos and labelmargin. If labelpos is None, no - label is created. Otherwise, a label is created and positioned - according to the value of labelpos and labelmargin. The label - is added to the parent using the grid() method, with childCols - and childRows indicating how many rows and columns the label - should span. Note that all other child widgets of the parent - must be added to the parent using the grid() method. The - createlabel() method may be called by derived classes during - megawidget construction.

- - -
- -
defineoptions(keywords, optionDefs, dynamicGroups = ())
-Create options for this megawidget. The optionDefs argument - defines the options. It is a sequence of 3-element tuples, - (name, default, callback), where name is the name of the - option, default is its default value and callback is the - function to call when the value of the option is set by a call to - configure(). The keywords argument should be the keyword - arguments passed in to the constructor of the megawidget. The user - may override the default value of an option by supplying a keyword - argument to the constructor.

-

If any option created by a base class is also defined by - optionDefs, then the derived class's default value will take - precedence over the base class's. If the callback field is not - None, then this will also override the callback set by the base - class.

- -

If callback is Pmw.INITOPT, then the option is an - initialisation option.

- -

The dynamicGroups argument contains a list of the groups of the - components created dynamically by this megawidget. If a group is - included in this list, then it not an error if a keyword argument - for the group is given to the constructor or to configure(), - even when no components with this group have been created.

- -

If defineoptions() is called, it must be called once in the - megawidget constructor before the call to the constructor of the - base class and there must be a matching call to - initialiseoptions() at the end of the constructor.

- - - -
- -
destroy()
-Destroy the hull component widget, if it exists, including all - of its children.

- - -
- -
destroycomponent(name)
-Remove the megawidget component called name. This method may be - called by derived classes to destroy a megawidget component. It - destroys the component widget and then removes all record of the - component from the megawidget.

- - -
- -
hulldestroyed()
-Return true if the Tk widget corresponding to the hull component - has been destroyed.

- - -
- -
initialiseoptions(dummy = None)
-Check keyword arguments and call option callback functions. This - method must be called, at the end of a megawidget constructor, if - and only if defineoptions() was also called in the constructor. - The dummy argument is not required, but is retained for - backwards compatibility.

-

It checks that all keyword arguments given to the constructor have - been used. If not, it raises an error indicating which arguments - were unused. A keyword is defined to be used if, during the - construction of a megawidget, it is defined in a call to - defineoptions() or addoptions() (by the megawidget or one of - its base classes), or it references, by name, a component of the - megawidget, or it references, by group, at least one component. - It also calls the configuration callback function for all options - that have a callback.

- -

This method is only effective when called by the constructor of - the leaf class, that is, the class in the class hierarchy which - first called defineoptions(). For all other classes in the - class hierarchy (base classes), the method returns immediately.

- - - -
- -
interior()
-Return the widget framing the interior space in which any children - of this megawidget should be created. By default, this returns - the hull component widget, if one was created, or None - otherwise. A subclass should use the widget returned by - interior() as the parent of any components or sub-widgets it - creates. Megawidgets which can be further subclassed, such as - Pmw.Dialog, should redefine this method to return the widget in - which subclasses should create children. The overall containing - widget is always available as the hull component.

- - -
- -
isinitoption(option)
-If option is an initialisation option, return true. Otherwise, - return false (the option is a configuration option). The option - argument must be an option of this megawidget, not an option of a - component. Otherwise an exception is raised.

- - -
- -
options()
-Return a sorted list of this megawidget's options. Each item in - the list is a 3-element tuple, (option, default, isinit), - where option is the name of the option, default is its default - value and isinit is true if the option is an initialisation - option.

- - -
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 22 May 1998 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/MegaToplevel.html b/Pmw/Pmw_1_2/doc/MegaToplevel.html deleted file mode 100644 index 53c1fe03..00000000 --- a/Pmw/Pmw_1_2/doc/MegaToplevel.html +++ /dev/null @@ -1,267 +0,0 @@ - - - - - - Pmw.MegaToplevel reference manual - - - - -

Pmw.MegaToplevel

- -
-

Name

-

Pmw.MegaToplevel() - - base class for megawidgets within a toplevel -

- - -
-

Inherits

-Pmw.MegaArchetype
-
-

Description

-

- This class creates a megawidget contained within a toplevel - window. It may be used directly to create a toplevel megawidget - or it may be used as a base class for more specialised toplevel - megawidgets, such as Pmw.Dialog. It creates a Tkinter.Toplevel - component, named hull, to act as the container of the megawidget. - The window class name for the hull widget is set to the - most-specific class name for the megawidget. Derived classes - specialise this class by creating other widget components as - children of the hull widget.

- -

The megawidget may be used as either a normal toplevel window or - as a modal dialog. Use show() and withdraw() for normal use - and activate() and deactivate() for modal dialog use. If the - window is deleted by the window manager while being shown - normally, the default behaviour is to destroy the window. If the - window is deleted by the window manager while the window is active - (ie: when used as a modal dialog), the window is deactivated. - Use the userdeletefunc() and usermodaldeletefunc() methods to - override these behaviours. Do not call protocol() to set the - WM_DELETE_WINDOW window manager protocol directly if you want to - use this window as a modal dialog.

- -

The currently active windows form a stack with the most recently - activated window at the top of the stack. All mouse and - keyboard events are sent to this top window. When it - deactivates, the next window in the stack will start to receive - events.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
activatecommand -
-If this is callable, it will be called whenever the megawidget is - activated by a call to activate(). The default is None.

- - -
- -
deactivatecommand -
-If this is callable, it will be called whenever the megawidget is - deactivated by a call to deactivate(). The default is None.

- - -
- -
master -
-This is used by the activate() method to control whether the - window is made transient during modal dialogs. See the - activate() method. The default is None.

- - -
- -
title -
-This is the title that the window manager displays in the title - bar of the window. The default is None.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Toplevel.

- - -
-
- -

Methods

-Only methods specific to this megawidget are described below. -For a description of its inherited methods, see the -manual for its base class -Pmw.MegaArchetype. -In addition, methods from the -Tkinter.Toplevel class -are forwarded by this megawidget to the -hull component. -

- -
activate(globalMode = 0, geometry = 'centerscreenfirst')
-Display the window as a modal dialog. This means that all mouse - and keyboard events go to this window and no other windows can - receive any events. If you do not want to restrict mouse and - keyboard events to this window, use the show() method instead.

-

If the BLT extension to Tk is present, a busy cursor will be - displayed on other toplevel windows, using Pmw.showbusycursor().

- -

The activate() method does not return until the deactivate() - method is called, when the window is withdrawn, the grab released - and the result returned.

- -

If globalMode is false, the window will grab control of the - pointer and keyboard, preventing any events from being delivered - to any other toplevel windows within the application. If - globalMode is true, the grab will prevent events from being - delivered to any other toplevel windows regardless of application. - Global grabs should be used sparingly, if at all.

- -

If globalMode is 'nograb', then no grab is performed. If BLT - is present, this will allow mouse and keyboard events to be - received by other windows whose exclude busycursor attribute has - been set to true by a call to Pmw.setbusycursorattributes(). - Note that if 'nograb' is used and BLT is not present, then all - other windows will receive mouse and keyboard events. This is - because, in plain Tk, there is no way to specify that two windows - (only) receive events. If your application may be used without - BLT, then do not use 'nograb'.

- -

When the window is displayed, it is positioned on the screen - according to geometry which may be one of:

- -
centerscreenfirst
The window will be centered the first time it is activated. - On subsequent activations it will be positioned in the same - position as the last time it was displayed, even if it has - been moved by the user.

- -
-
centerscreenalways
The window will be be centered on the screen (halfway across - and one third down).

- -
-
first + spec
It is assumed that the rest of the argument (after 'first') - is a standard geometry specification. The window will be - positioned using this specification the first time it is - activated. On subsequent activations it will be positioned in - the same position as the last time it was displayed, even if - it has been moved by the user. For example, - geometry = first+100+100 will initially display the window - at position (100,100). Other calls to activate() will not - change the previous position of the window.

- -
-
spec
This is a standard geometry specification. The window will be - be positioned using this specification.

- -
-

If the BLT Tcl extension library is present, a clock cursor - will be displayed until the window is deactivated.

- -

If the activatecommand option is callable, it is called just - before the window begins to wait for the result.

- -

If the master option is not None, the window will become a - transient window of master, which should be a toplevel window. - If master has the special value of 'parent', the master is the - toplevel window of the window's parent.

- - - -
- -
active()
-Return true if the megawidget is currently active (that is, - activate() is currently waiting for a result to be passed to it - by a call to deactivate()).

- - -
- -
deactivate(result = None)
-This should be called while a call to activate() is waiting. It - will withdraw the window, release the grab and cause the - activate() call to return with the value of result.

-

If the deactivatecommand option is callable, it is called just - before the deactivate() method returns.

- - - -
- -
destroy()
-Destroy the hull component widget, including all of its - children. If the megawidget is currently active, deactivate it.

- - -
- -
show(master = None)
-Make the window visible. This raises or deiconifies the toplevel - window. If the window has previously been shown it will remain in - the same position. This means that calling withdraw() then - show() will not move the window, whereas calling withdraw() - then deiconify() may change the window's position. (This may - depend on the behaviour of the window manager.)

- - -
- -
userdeletefunc(func = None)
-If func is None, return the function that will be called - when the window is deleted by the window manager while being - displayed normally. If func is not None, set this function to - func. By default, the function is self.destroy.

- - -
- -
usermodaldeletefunc(func = None)
-If func is None, return the function that will be called - when the window is deleted by the window manager while it is - active (ie: when being used as a modal dialog). If func is not - None, set this function to func. By default, the function is - self.deactivate.

- - -
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 22 May 1998 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/MegaWidget.html b/Pmw/Pmw_1_2/doc/MegaWidget.html deleted file mode 100644 index d18698bb..00000000 --- a/Pmw/Pmw_1_2/doc/MegaWidget.html +++ /dev/null @@ -1,83 +0,0 @@ - - - - - - Pmw.MegaWidget reference manual - - - - -

Pmw.MegaWidget

- -
-

Name

-

Pmw.MegaWidget() - - base class for megawidgets within a frame -

- - -
-

Inherits

-Pmw.MegaArchetype
-
-

Description

-

- This class creates a megawidget contained within a Tkinter.Frame - window. The class acts as the base class for megawidgets that are - not contained in their own toplevel window, such as Pmw.ButtonBox and - Pmw.ComboBox. It creates a Tkinter.Frame component, named hull, - to act as the container of the megawidget. The window class name - for the hull widget is set to the most-specific class name for - the megawidget. Derived classes specialise this class by - creating other widget components as children of the hull widget.

- -

- - -
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Frame.

- - -
-
- -

Methods

-This megawidget has no methods of its own. -For a description of its inherited methods, see the -manual for its base class -Pmw.MegaArchetype. -In addition, methods from the -Tkinter.Frame class -are forwarded by this megawidget to the -hull component. -

-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 22 May 1998 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/MenuBar.gif b/Pmw/Pmw_1_2/doc/MenuBar.gif deleted file mode 100644 index aa7a7bf8..00000000 Binary files a/Pmw/Pmw_1_2/doc/MenuBar.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/MenuBar.html b/Pmw/Pmw_1_2/doc/MenuBar.html deleted file mode 100644 index e2c04a6c..00000000 --- a/Pmw/Pmw_1_2/doc/MenuBar.html +++ /dev/null @@ -1,399 +0,0 @@ - - - - - - Pmw.MenuBar reference manual - - - - -

Pmw.MenuBar

- -
-
-

Name

-

Pmw.MenuBar() - - manager megawidget for menu buttons and menus -

- - -
-

Inherits

-Pmw.MegaWidget
-
-

Description

-

- A menu bar is a container megawidget which manages a number of - menu buttons and dropdown menus. There - are methods to add menu buttons and menus to the menu bar and for - adding menu items to the menus. Menu buttons may be added to the - left or right of the megawidget. Each menu button and menu item may - have help text to be displayed by a Pmw.Balloon. Each menu - and cascaded menu (sub-menu) is referenced by name which is - supplied on creation.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
balloon -
-Specifies a Pmw.Balloon to display the help text for menu - buttons and menu items. If None, no help is displayed. If the - balloon has an associated Pmw.MessageBar, the help text will also be - displayed there. The default is None.

- - -
- -
hotkeys -
-Initialisation option. If true, keyboard accelerators will be assigned to each menu - button and menu item. Keyboard accelerators can be used to access - the menus without using the mouse. The accelerator character is - always one of the alphanumeric characters in the text label of the - menu or menu item and is indicated by an underline.

-

To select a menu, simultaneously press the <Alt> key and the - accelerator character indicated on a menu button. The arrows keys - can then be used to select other menus and menu items. To invoke a - menu item, press <Return> or press the accelerator character - indicated on the menu item.

- -

Each accelerator character will be assigned automatically unless - traverseSpec is supplied to the addmenu(), addmenuitem() or - addcascademenu() methods. The automatically selected - accelerator character for a menu button (or menu item) is the - first character in the label text that has not already been used - as an accelerator for a menu button (or in the menu containing the - menu item).

- -

If traverseSpec is given, it must be either an integer or a - character. If an integer, it specifies the index of the character - in the label text to use as the accelerator character. If a - character, it specifies the character to use as the accelerator - character. The default is 1.

- - - -
- -
padx -
-Initialisation option. Specifies a padding distance to leave between each menu button in - the x direction and also between the menu buttons and the outer - edge of the menu bar. The default is 0.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Frame.

- - -
-
-

Dynamic components

-

- Menu button components are created dynamically by the - addmenu() method. By default, these are of type - Tkinter.Menubutton and are created with a component group of - Button.

- -

Menu components are created dynamically by the addmenu() and - addcascademenu() methods. By default, these are of type - Tkinter.Menu and are created with a component group of Menu.

-

- - - -
- -

Methods

-Only methods specific to this megawidget are described below. -For a description of its inherited methods, see the -manual for its base class -Pmw.MegaWidget. -

- -
addcascademenu(parentMenuName, menuName, statusHelp = '', traverseSpec = None, **kw)
-Add a cascade menu (sub-menu) to the menu parentMenuName. The - menuName argument must not be the same as any menu already - created using the addmenu() or addcascademenu() methods.

-

A menu item in the parent menu is created (with the - add_cascade() method of the parent menu) using all keyword - arguments except tearoff.

- -

If the label keyword argument is not given, the label option - of the menu item defaults to menuName. If the underline - keyword argument is not given (and the hotkeys megawidget option - is true) the underline option is determined as described under - hotkeys and is used to specify the keyboard accelerator.

- -

The statusHelp argument is used as the help string for the menu - item. This is displayed using the showstatus() method of the - balloon.

- -

The tearoff keyword argument, if present, is passed to the - constructor of the menu. The menu is created as a component named - menuName-menu.

- - - -
- -
addmenu(menuName, balloonHelp, statusHelp = None, side = 'left', traverseSpec = None, **kw)
-Add a menu button and its associated menu to the menu bar. The - menuName argument must not be the same as any menu already - created using the addmenu() or addcascademenu() methods.

-

Any keyword arguments present (except tearoff) will be passed to - the constructor of the menu button. If the text keyword - argument is not given, the text option of the menu button - defaults to menuName. If the underline keyword argument is - not given (and the hotkeys megawidget option is true) the - underline option is determined as described under hotkeys and - is used to specify the keyboard accelerator. Each menu button is - packed into the menu bar using the given side, which should be - either left or right. The menu button is created as a - component named menuName-button.

- -

If the balloon option has been defined, balloonHelp and - statusHelp are passed to the balloon as the help strings for the - menu button. See the bind() method of Pmw.Balloon for how these - strings may be displayed.

- -

The tearoff keyword argument, if present, is passed to the - constructor of the menu. The menu is created as a component named - menuName-menu.

- - - -
- -
addmenuitem(menuName, itemType, statusHelp = '', traverseSpec = None, **kw)
-Add a menu item to the menu menuName. The kind of menu item is - given by itemType and may be one of command, separator, - checkbutton, radiobutton or cascade (although cascade menus - are better added using the addcascademenu() method). Any - keyword arguments present will be passed to the menu when creating - the menu item. See Tkinter.Menu for the valid options for each - item type. In addition, a keyboard accelerator may be - automatically given to the item, as described under hotkeys.

-

When the mouse is moved over the menu item, the helpString will - be displayed by the balloon's statuscommand.

- - - -
- -
deletemenu(menuName)
-Delete the menu menuName and all its items. The menu may either - be a toplevel menu (in which case the corresponding menu button is - also deleted) or a cascade menu.

- - -
- -
deletemenuitems(menuName, start, end = None)
-Delete menu items from the menu menuName. If end is not - given, the start item is deleted. Otherwise all items from - start to end are deleted.

- - -
- -
disableall()
-Disable all toplevel menus.

- - -
- -
enableall()
-Enable all toplevel menus.

- - -
-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-        # Create the Balloon.
-        self.balloon = Pmw.Balloon(parent)
-
-        # Create and pack the MenuBar.
-        menuBar = Pmw.MenuBar(parent,
-                hull_relief = 'raised',
-                hull_borderwidth = 1,
-                balloon = self.balloon)
-        menuBar.pack(fill = 'x')
-        self.menuBar = menuBar
-
-        # Add some buttons to the MenuBar.
-        menuBar.addmenu('File', 'Close this window or exit')
-        menuBar.addmenuitem('File', 'command', 'Close this window',
-                command = PrintOne('Action: close'),
-                label = 'Close')
-        menuBar.addmenuitem('File', 'separator')
-        menuBar.addmenuitem('File', 'command', 'Exit the application',
-                command = PrintOne('Action: exit'),
-                label = 'Exit')
-
-        menuBar.addmenu('Edit', 'Cut, copy or paste')
-        menuBar.addmenuitem('Edit', 'command', 'Delete the current selection',
-                command = PrintOne('Action: delete'),
-                label = 'Delete')
-
-        menuBar.addmenu('Options', 'Set user preferences')
-        menuBar.addmenuitem('Options', 'command', 'Set general preferences',
-                command = PrintOne('Action: general options'),
-                label = 'General...')
-
-        # Create a checkbutton menu item.
-        self.toggleVar = Tkinter.IntVar()
-        # Initialise the checkbutton to 1:
-        self.toggleVar.set(1)
-        menuBar.addmenuitem('Options', 'checkbutton', 'Toggle me on/off',
-                label = 'Toggle',
-                command = self._toggleMe,
-                variable = self.toggleVar)
-        self._toggleMe()
-
-        menuBar.addcascademenu('Options', 'Size',
-                'Set some other preferences', traverseSpec = 'z', tearoff = 1)
-        for size in ('tiny', 'small', 'average', 'big', 'huge'):
-            menuBar.addmenuitem('Size', 'command', 'Set size to ' + size,
-                    command = PrintOne('Action: size ' + size),
-                    label = size)
-
-        menuBar.addmenu('Help', 'User manuals', side = 'right')
-        menuBar.addmenuitem('Help', 'command', 'About this application',
-                command = PrintOne('Action: about'),
-                label = 'About...')
-
-        # Create and pack the main part of the window.
-        self.mainPart = Tkinter.Label(parent,
-                text = 'This is the\nmain part of\nthe window',
-                background = 'black',
-                foreground = 'white',
-                padx = 30,
-                pady = 30)
-        self.mainPart.pack(fill = 'both', expand = 1)
-
-        # Create and pack the MessageBar.
-        self.messageBar = Pmw.MessageBar(parent,
-                entry_width = 40,
-                entry_relief='groove',
-                labelpos = 'w',
-                label_text = 'Status:')
-        self.messageBar.pack(fill = 'x', padx = 10, pady = 10)
-        self.messageBar.message('state', 'OK')
-
-        buttonBox = Pmw.ButtonBox(parent)
-        buttonBox.pack(fill = 'x')
-        buttonBox.add('Disable\nall', command = menuBar.disableall)
-        buttonBox.add('Enable\nall', command = menuBar.enableall)
-        buttonBox.add('Create\nmenu', command = self.add)
-        buttonBox.add('Delete\nmenu', command = self.delete)
-        buttonBox.add('Create\nitem', command = self.additem)
-        buttonBox.add('Delete\nitem', command = self.deleteitem)
-
-        # Configure the balloon to displays its status messages in the
-        # message bar.
-        self.balloon.configure(statuscommand = self.messageBar.helpmessage)
-
-        self.testMenuList = []
-
-    def _toggleMe(self):
-        print 'Toggle value:', self.toggleVar.get()
-
-    def add(self):
-        if len(self.testMenuList) == 0:
-            num = 0
-        else:
-            num = self.testMenuList[-1]
-        num = num + 1
-        name = 'Menu%d' % num
-        self.testMenuList.append(num)
-
-        self.menuBar.addmenu(name, 'This is ' + name)
-
-    def delete(self):
-        if len(self.testMenuList) == 0:
-            self.menuBar.bell()
-        else:
-            num = self.testMenuList[0]
-            name = 'Menu%d' % num
-            del self.testMenuList[0]
-            self.menuBar.deletemenu(name)
-
-    def additem(self):
-        if len(self.testMenuList) == 0:
-            self.menuBar.bell()
-        else:
-            num = self.testMenuList[-1]
-            menuName = 'Menu%d' % num
-            menu = self.menuBar.component(menuName + '-menu')
-            if menu.index('end') is None:
-                label = 'item X'
-            else:
-                label = menu.entrycget('end', 'label') + 'X'
-            self.menuBar.addmenuitem(menuName, 'command', 'Help for ' + label,
-                    command = PrintOne('Action: ' + menuName + ': ' + label),
-                    label = label)
-            
-    def deleteitem(self):
-        if len(self.testMenuList) == 0:
-            self.menuBar.bell()
-        else:
-            num = self.testMenuList[-1]
-            menuName = 'Menu%d' % num
-            menu = self.menuBar.component(menuName + '-menu')
-            if menu.index('end') is None:
-                self.menuBar.bell()
-            else:
-                self.menuBar.deletemenuitems(menuName, 0)
-            
-class PrintOne:
-    def __init__(self, text):
-        self.text = text
-
-    def __call__(self):
-        print self.text
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 22 April 2000 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/MessageBar.gif b/Pmw/Pmw_1_2/doc/MessageBar.gif deleted file mode 100644 index 0dc44465..00000000 Binary files a/Pmw/Pmw_1_2/doc/MessageBar.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/MessageBar.html b/Pmw/Pmw_1_2/doc/MessageBar.html deleted file mode 100644 index 69be04e7..00000000 --- a/Pmw/Pmw_1_2/doc/MessageBar.html +++ /dev/null @@ -1,302 +0,0 @@ - - - - - - Pmw.MessageBar reference manual - - - - -

Pmw.MessageBar

- -
-
-

Name

-

Pmw.MessageBar() - - information line for displaying short messages -

- - -
-

Inherits

-Pmw.MegaWidget
-
-

Description

-

- A message bar contains a single-line message display area. Messages - of several different types may displayed. Messages are cleared - after a period defined for each message type. Each message type - has a priority so that if the application attempts to display more - than one message at a time, the message with the highest priority - will be displayed. Messages may be accompanied by a number of - audible bells.

- -

This megawidget can be used for both interactive help messages - (when the mouse enters certain widgets) and also for other general - messages.

- -

To perform the help function it can cooperate with the Pmw.Balloon - megawidget so that the programmer (or user) can choose either - balloon help, message bar help, both or neither.

- -

This megawidget supports a configurable number of message types. - The default types include 'state', 'help', 'usererror' and - 'systemerror'. The difference between these are the length of - time they are displayed, the number of bells that are rung and the - priority of the message. For example, the 'help' message type - is lower in priority than the 'usererror', so that error - messages will always be displayed in preference to help messages - regardless of the order the messages are created. The 'state' - message type is lowest in priority but has no timeout, so it - should contain messages describing the current state of the - application, such as Waiting for database connection or 'Waiting - for file to be unlocked'. Generally this should be set to the - empty string when the application is running normally. By default - the help messages (with message type 'help') time out after 5 - seconds, so that if the cursor happens to be left over a widget, - the application state will be redisplayed after a short time.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
labelmargin -
-Initialisation option. If the labelpos option is not None, this specifies the - distance between the label component and the rest of the - megawidget. The default is 0.

- - -
- -
labelpos -
-Initialisation option. Specifies where to place the label component. If not - None, it should be a concatenation of one or two of the - letters 'n', 's', 'e' and 'w'. The first letter - specifies on which side of the megawidget to place the label. - If a second letter is specified, it indicates where on that - side to place the label. For example, if labelpos is 'w', - the label is placed in the center of the left hand side; if - it is 'wn', the label is placed at the top of the left - hand side; if it is 'ws', the label is placed at the - bottom of the left hand side.

-

If None, a label component is not created. The default is None.

- - - -
- -
messagetypes -
-Initialisation option. This defines what message types are supported by the message bar - and the characteristics of those message types. It is a - dictionary where the key is a string specifying a message type and - the value is a tuple of four integers, (priority, showtime, - bells, logmessage), where priority is the rank of the - message type, showtime is the number of seconds to display - messages of this message type, bells is the number of audible - bells to ring and logmessage is a boolean - specifying whether this message should be logged for retrieval - later. Messages with a higher priority are displayed in - preference to those with lower priority. If a high priority - message times out (because it has been displayed for showtime - seconds), then a lower priority message may be displayed. A - showtime of 0 means that the message will never time out and - is useful for displaying messages describing the current state of - the application as opposed to messages describing events. Logging - is not currently implemented. The default is

-
 {
-     'systemerror'  : (5, 10, 2, 1),
-     'usererror'    : (4, 5, 1, 0),
-     'busy'         : (3, 0, 0, 0),
-     'systemevent'  : (2, 5, 0, 0),
-     'userevent'    : (2, 5, 0, 0),
-     'help'         : (1, 5, 0, 0),
-     'state'        : (0, 0, 0, 0),
- }
- - - -
- -
silent -
-If true, no audible bells will sound, regardless of the value for - bells defined in the messagetypes option. The default is 0.

- - -
- -
sticky -
-Initialisation option. The default is 'ew'.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
entry -
-The widget where the messages are displayed. Long messages may be - scrolled horizontally by dragging with the middle mouse button. By default, this component is a Tkinter.Entry.

- - -
- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Frame.

- - -
- -
label -
-If the labelpos option is not None, this component is - created as a text label for the megawidget. See the - labelpos option for details. Note that to set, for example, - the text option of the label, you need to use the label_text - component option. By default, this component is a Tkinter.Label.

- - -
-
- -

Methods

-Only methods specific to this megawidget are described below. -For a description of its inherited methods, see the -manual for its base class -Pmw.MegaWidget. -In addition, methods from the -Tkinter.Entry class -are forwarded by this megawidget to the -entry component. -

- -
helpmessage(text)
-A convenience method to display text in the message bar - according to the characteristics defined by the help message type. - Equivalent to message('help', text).

- - -
- -
message(type, text)
-Display text in the message bar according to the characteristics - defined by the type message type, as discussed under - messagetypes.

- - -
- -
resetmessages(type)
-Clear the type message and all message types with a lower - priority, except permanent messages, such as state. This is - useful to clear the busy message and any outstanding event and - help messages.

- - -
-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-        # Create and pack the MessageBar.
-        self._messagebar = Pmw.MessageBar(parent,
-                entry_width = 40,
-                entry_relief='groove',
-                labelpos = 'w',
-                label_text = 'Status:')
-        self._messagebar.pack(side = 'bottom', fill = 'x',
-                expand = 1, padx = 10, pady = 10)
-
-        # Create and pack the ScrolledListBox to change the MessageBar.
-        self.box = Pmw.ScrolledListBox(parent,
-                listbox_selectmode='single',
-                items=('state', 'help', 'userevent', 'systemevent',
-                        'usererror', 'systemerror', 'busy',),
-                label_text='Message type',
-                labelpos='n',
-                selectioncommand=self.selectionCommand)
-        self.box.pack(fill = 'both', expand = 'yes', padx = 10, pady = 10)
-
-        self._index = 0
-        self._stateCounter = 0
-
-    def selectionCommand(self):
-        sels = self.box.getcurselection()
-        if len(sels) > 0:
-            self._index = self._index + 1
-            messagetype = sels[0]
-            if messagetype == 'state':
-                self._stateCounter = (self._stateCounter + 1) % 3
-                text = stateMessages[self._stateCounter]
-                if text != '':
-                    text = text + ' (' + messagetype + ')'
-                self._messagebar.message('state', text)
-            else:
-                text = messages[messagetype]
-                text = text + ' (' + messagetype + ')'
-                self._messagebar.message(messagetype, text)
-                if messagetype == 'busy':
-                    Pmw.showbusycursor()
-                    self.box.after(2000)
-                    Pmw.hidebusycursor()
-                    self._messagebar.resetmessages('busy')
-                    text = 'All files successfully removed'
-                    text = text + ' (userevent)'
-                    self._messagebar.message('userevent', text)
-
-
-messages = {
-    'help': 'Save current file',
-    'userevent': 'Saving file "foo"',
-    'busy': 'Busy deleting all files from file system ...',
-    'systemevent': 'File "foo" saved',
-    'usererror': 'Invalid file name "foo/bar"',
-    'systemerror': 'Failed to save file: file system full',
-}
-
-stateMessages = {
-    0: '',
-    1: 'Database is down',
-    2: 'Waiting for reply from database',
-}
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home - -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/MessageDialog.gif b/Pmw/Pmw_1_2/doc/MessageDialog.gif deleted file mode 100644 index f6ac1643..00000000 Binary files a/Pmw/Pmw_1_2/doc/MessageDialog.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/MessageDialog.html b/Pmw/Pmw_1_2/doc/MessageDialog.html deleted file mode 100644 index f3e35884..00000000 --- a/Pmw/Pmw_1_2/doc/MessageDialog.html +++ /dev/null @@ -1,326 +0,0 @@ - - - - - - Pmw.MessageDialog reference manual - - - - -

Pmw.MessageDialog

- -
-
-

Name

-

Pmw.MessageDialog() - - a dialog displaying a text message and an icon -

- - -
-

Inherits

-Pmw.Dialog
-
-

Description

-

- A message dialog is a dialog window which displays a simple - message to the user along with one or more buttons to press.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
activatecommand -
-If this is callable, it will be called whenever the megawidget is - activated by a call to activate(). The default is None.

- - -
- -
borderx -
-Initialisation option. The padding to the left and right of the text message and icon. The default is 20.

- - -
- -
bordery -
-Initialisation option. The padding above and below the text message and icon. The default is 20.

- - -
- -
buttonboxpos -
-Initialisation option. Specifies on which side of the dialog window to place the button - box. Must be one of 'n', 's', 'e' or 'w'. The default is 's'.

- - -
- -
buttons -
-This must be a tuple or a list and specifies the names on the - buttons in the button box. The default is ('OK',).

- - -
- -
command -
-Specifies a function to call whenever a button in the button box - is invoked or the window is deleted by the window manager. The - function is called with a single argument, which is the name of - the button which was invoked, or None if the window was deleted - by the window manager.

-

If the value of command is not callable, the default behaviour - is to deactivate the window if it is active, or withdraw the - window if it is not active. If it is deactivated, deactivate() - is called with the button name or None as described above. The default is None.

- - - -
- -
deactivatecommand -
-If this is callable, it will be called whenever the megawidget is - deactivated by a call to deactivate(). The default is None.

- - -
- -
defaultbutton -
-Specifies the default button in the button box. If the <Return> - key is hit when the dialog has focus, the default button will be - invoked. If defaultbutton is None, there will be no default - button and hitting the <Return> key will have no effect. The default is None.

- - -
- -
iconmargin -
-Initialisation option. The padding between the text message and icon. The default is 20.

- - -
- -
iconpos -
-Initialisation option. Specifies on which side of the text message to place the icon. - Must be one of 'n', 's', 'e' or 'w'. The default is None.

- - -
- -
master -
-This is used by the activate() method to control whether the - window is made transient during modal dialogs. See the - activate() method. The default is 'parent'.

- - -
- -
separatorwidth -
-Initialisation option. If this is greater than 0, a separator line with the specified - width will be created between the button box and the child site, - as a component named separator. Since the default border of the - button box and child site is raised, this option does not - usually need to be set for there to be a visual separation between - the button box and child site. The default is 0.

- - -
- -
title -
-This is the title that the window manager displays in the title - bar of the window. The default is None.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
buttonbox -
-This is the button box containing the buttons for the dialog. By - default it is created with the options - (hull_borderwidth = 1, hull_relief = 'raised'). By default, this component is a Pmw.ButtonBox.

- - -
- -
dialogchildsite -
-This is the child site for the dialog, which may be used to - specialise the megawidget by creating other widgets within it. By - default it is created with the options - (borderwidth = 1, relief = 'raised'). By default, this component is a Tkinter.Frame.

- - -
- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Toplevel.

- - -
- -
icon -
-If the iconpos option is not None, this component is created - to contain the icon label for the dialog. To display a bitmap as - an icon, set the icon_bitmap component option to any of the - forms acceptable to Tk, such as 'warning' or 'error'. By default, this component is a Tkinter.Label.

- - -
- -
message -
-The label to contain the text message for the dialog. To set - the text, use the message_text component option. By default, this component is a Tkinter.Label.

- - -
- -
separator -
-If the separatorwidth initialisation option is non-zero, the - separator component is the line dividing the area between the - button box and the child site. By default, this component is a Tkinter.Frame.

- - -
-
- -

Methods

-This megawidget has no methods of its own. -For a description of its inherited methods, see the -manual for its base class -Pmw.Dialog. -

-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-        self.parent = parent
-
-        # Create dialog 1.
-        self.dialog1 = Pmw.MessageDialog(parent,
-            title = 'Simple message dialog',
-            defaultbutton = 0,
-            message_text = 'A simple message dialog\nwith no callback.')
-        self.dialog1.iconname('Simple message dialog')
-        self.dialog1.withdraw()
-
-        # Create dialog 2.
-        self.dialog2 = Pmw.MessageDialog(parent,
-            title = 'Bell ringing dialog',
-            message_text = 'This message dialog\nwill ring the bell ' +
-                'when\nyou click on the buttons.',
-            iconpos = 'w',
-            icon_bitmap = 'error',
-            command = self.execute2,
-            buttons = ('One', 'Two', 'Three', 'Close'))
-        self.dialog2.iconname('Bell ringing dialog')
-        self.dialog2.withdraw()
-
-        # Create dialog 3.
-        self.dialog3 = Pmw.MessageDialog(parent,
-            title = 'Vertical button dialog',
-            message_text = 'This message dialog\nhas the buttons on the\n' +
-                'right hand side.',
-            buttonboxpos = 'e',
-            iconpos = 'n',
-            icon_bitmap = 'warning',
-            buttons = ('Goodbye', 'Au revoir', 'Sayonara', 'Close'),
-            defaultbutton = 'Close')
-        self.dialog3.iconname('Vertical button dialog')
-        self.dialog3.withdraw()
-
-        # Create some buttons to launch the dialogs.
-        w = Tkinter.Button(parent, text = 'Simple dialog',
-                command = lambda self = self:
-                        self.dialog1.activate(geometry = 'first+100+100'))
-        w.pack(padx = 8, pady = 8)
-
-        w = Tkinter.Button(parent, text = 'Bell ringing dialog',
-                command = self.dialog2.activate)
-        w.pack(padx = 8, pady = 8)
-
-        w = Tkinter.Button(parent, text = 'Vertical buttons',
-                command = self.dialog3.activate)
-        w.pack(padx = 8, pady = 8)
-
-        w = Tkinter.Button(parent, text = 'On the fly dialog',
-                command = self._createOnTheFly)
-        w.pack(padx = 8, pady = 8)
-
-    def execute2(self, result):
-        print 'You clicked on', result
-        if result is None:
-            self.dialog2.deactivate(result)
-        elif result == 'Close':
-            self.dialog2.deactivate(result)
-        else:
-            for count in range({'One': 1, 'Two': 2, 'Three': 3}[result]):
-                if count != 0:
-                    self.dialog2.after(200)
-                self.dialog2.bell()
-
-    def _createOnTheFly(self):
-        dialog = Pmw.MessageDialog(self.parent,
-            title = 'On the fly dialog',
-            defaultbutton = 0,
-            buttons = ('OK', 'Apply', 'Cancel', 'Help'),
-            message_text = 'This dialog was created when you clicked ' +
-                'on the button.')
-        dialog.iconname('Simple message dialog')
-        result = dialog.activate()
-
-        print 'You selected', result
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 18 May 2002 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/NoteBook.gif b/Pmw/Pmw_1_2/doc/NoteBook.gif deleted file mode 100644 index 206a88d3..00000000 Binary files a/Pmw/Pmw_1_2/doc/NoteBook.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/NoteBook.html b/Pmw/Pmw_1_2/doc/NoteBook.html deleted file mode 100644 index 38601f7e..00000000 --- a/Pmw/Pmw_1_2/doc/NoteBook.html +++ /dev/null @@ -1,344 +0,0 @@ - - - - - - Pmw.NoteBook reference manual - - - - -

Pmw.NoteBook

- -
-
-

Name

-

Pmw.NoteBook() - - a set of tabbed pages -

- - -
-

Inherits

-Pmw.MegaArchetype
-
-

Description

-

- A notebook contains a set of tabbed pages. At any one time only - one of these pages (the selected page) is visible, with the - other pages being hidden "beneath" it. Another page in the - notebook may be displayed by clicking on the tab attached to the - page. The tabs are displayed along the top edge.

- -

Optionally, the notebook may be displayed without tabs. In this - case, another selection widget, such as Pmw.OptionMenu, may be used - to select the pages.

- -

This megawidget is derived from Pmw.MegaArchetype (not Pmw.MegaWidget - like most other megawidgets), with the hull class being - Tkinter.Canvas.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
arrownavigation -
-Initialisation option. If true and a tab button has the keyboard focus, then the Left and - Right arrow keys can be used to select the page before or after - the tab button with the focus. The default is 1.

- - -
- -
borderwidth -
-Initialisation option. The width of the border drawn around each tab and around the - selected page. The default is 2.

- - -
- -
createcommand -
-Specifies a function to call when a page is selected for the first - time. The function is called with a single argument, which is the - name of the selected page, and is called before the raisecommand - function. This allows the creation of the page contents to be - deferred until the page is first displayed. The default is None.

- - -
- -
lowercommand -
-Specifies a function to call when the selected page is replaced - with a new selected page. The function is called with a single - argument, which is the name of the previously selected page, and - is called before the createcommand or raisecommand functions. The default is None.

- - -
- -
pagemargin -
-Initialisation option. The margin (in pixels) around the selected page inside the - notebook's page border. The default is 4.

- - -
- -
raisecommand -
-Specifies a function to call when a new page is selected. The - function is called with a single argument, which is the name of - the selected page. The default is None.

- - -
- -
tabpos -
-Initialisation option. Specifies the location of the tabs. If 'n', tabs are created - for each page and positioned at the top of the notebook. If - None, no tabs are created, in which case another selection - widget can be used to select pages by calling the selectpage() - method. The default is 'n'.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
hull -
-This acts as the body for the megawidget. The contents of the - megawidget are created as canvas items and positioned in the - hull using the canvas coordinate system. By default, this component is a Tkinter.Canvas.

- - -
-
-

Dynamic components

-

- Page and tab components are created dynamically by the add() - and insert() methods. By default, the pages are of type - Tkinter.Frame and are created with a component group of Page - and the tabs are of type Tkinter.Button and are created with a - component group of Tab.

-

- - - -
- -

Methods

-Only methods specific to this megawidget are described below. -For a description of its inherited methods, see the -manual for its base class -Pmw.MegaArchetype. -In addition, methods from the -Tkinter.Canvas class -are forwarded by this megawidget to the -hull component. -

- -
add(pageName, **kw)
-Add a page at the end of the notebook. See the insert() method - for full details.

- - -
- -
delete(*pageNames)
-Delete the pages given by pageNames from the notebook. Each of - the pageNames may have any of the forms accepted by the - index() method.

-

If the currently selected page is deleted, then the next page, in - index order, is selected. If the end page is deleted, then the - previous page is selected.

- - - -
- -
getcurselection()
-Return the name of the currently selected page.

- - -
- -
index(index, forInsert = 0)
-Return the numerical index of the page corresponding to index. - This may be specified in any of the following forms:

-
name
Specifies the page labelled name.

- -
-
number
Specifies the page numerically, where 0 corresponds to - the first page.

- -
-
Pmw.END
Specifies the last page.

- -
-
Pmw.SELECT
Specifies the currently selected page.

- -
-

If forInsert is true, Pmw.END returns the number of pages - rather than the index of the last page.

- - - -
- -
insert(pageName, before = 0, **kw)
-Add a page to the notebook as a component named pageName. The - page is added just before the page specified by before, which - may have any of the forms accepted by the index() method. If - tabpos is not None, also create a tab as a component named - pageName-tab. Keyword arguments prefixed with page_ or - tab_ are passed to the respective constructors when creating the - page or tab. If the tab_text keyword argument is not given, the - text option of the tab defaults to pageName. If a page is - inserted into an empty notebook, the page is selected. To add a - page to the end of the notebook, use add(). The method returns - the pageName component widget.

- - -
- -
nextpage(pageIndex = None)
-If pageIndex is None, then select the page after the - currently selected page. Otherwise select the page after - pageIndex, which may have any of the forms accepted by the - index() method.

- - -
- -
page(pageIndex)
-Return the frame component widget of the page pageIndex, where - pageIndex may have any of the forms accepted by the index() - method.

- - -
- -
pagenames()
-Return a list of the names of the pages, in display order.

- - -
- -
previouspage(pageIndex = None)
-If pageIndex is None, then select the page before the - currently selected page. Otherwise select the page before - pageIndex, which may have any of the forms accepted by the - index() method.

- - -
- -
recolorborders()
-Change the color of the page and tab borders. This method is - required because the borders are created as canvas polygons and - hence do not respond to normal color changing techniques, such as - Pmw.Color.changecolor().

- - -
- -
selectpage(page)
-Select page to be the currently selected page. The page will be - raised and the previous selected page will be lowered.

- - -
- -
setnaturalsize(pageNames = None)
-Set the width and height of the notebook to be the maximum - requested width and height of the pages specified by pageNames. - If pageNames is None, the size of all pages are used to - determine the size of the notebook. Otherwise, pageNames must - be a list of page names whose sizes are to be used to determine - the size of the notebook. This method should be called after all - pages and their contents have been created. It calls - update_idletasks() so that the width and height of the pages can - be determined. This may cause the notebook to flash onto the - screen at the default size before resizing to the natural size.

- - -
- -
tab(pageIndex)
-Return the tab component widget of the page pageIndex, where - pageIndex may have any of the forms accepted by the index() - method. If tabpos is None, return None.

- - -
-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-        # Create and pack the NoteBook.
-        notebook = Pmw.NoteBook(parent)
-        notebook.pack(fill = 'both', expand = 1, padx = 10, pady = 10)
-
-        # Add the "Appearance" page to the notebook.
-        page = notebook.add('Appearance')
-        notebook.tab('Appearance').focus_set()
-
-        # Create the "Toolbar" contents of the page.
-        group = Pmw.Group(page, tag_text = 'Toolbar')
-        group.pack(fill = 'both', expand = 1, padx = 10, pady = 10)
-        b1 = Tkinter.Checkbutton(group.interior(), text = 'Show toolbar')
-        b1.grid(row = 0, column = 0)
-        b2 = Tkinter.Checkbutton(group.interior(), text = 'Toolbar tips')
-        b2.grid(row = 0, column = 1)
-
-        # Create the "Startup" contents of the page.
-        group = Pmw.Group(page, tag_text = 'Startup')
-        group.pack(fill = 'both', expand = 1, padx = 10, pady = 10)
-        home = Pmw.EntryField(group.interior(), labelpos = 'w',
-            label_text = 'Home page location:')
-        home.pack(fill = 'x', padx = 20, pady = 10)
-
-        # Add two more empty pages.
-        page = notebook.add('Helpers')
-        page = notebook.add('Images')
-
-        notebook.setnaturalsize()
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 30 October 1999 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/OptionMenu.gif b/Pmw/Pmw_1_2/doc/OptionMenu.gif deleted file mode 100644 index a36b151e..00000000 Binary files a/Pmw/Pmw_1_2/doc/OptionMenu.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/OptionMenu.html b/Pmw/Pmw_1_2/doc/OptionMenu.html deleted file mode 100644 index e1e0a6b6..00000000 --- a/Pmw/Pmw_1_2/doc/OptionMenu.html +++ /dev/null @@ -1,289 +0,0 @@ - - - - - - Pmw.OptionMenu reference manual - - - - -

Pmw.OptionMenu

- -
-
-

Name

-

Pmw.OptionMenu() - - single item selection megawidget -

- - -
-

Inherits

-Pmw.MegaWidget
-
-

Description

-

- An option menu consists of a menu button - and an associated menu which pops up when the button is pressed. - The text displayed in the menu button is updated whenever an item - is selected in the menu. The currently selected value can be - retrieved from the megawidget.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
command -
-Specifies a function to call whenever a menu item is selected or - the invoke() method is called. The function is called with the - currently selected value as its single argument. The default is None.

- - -
- -
initialitem -
-Initialisation option. Specifies the initial selected value. This option is treated in - the same way as the index argument of the setitems() method. The default is None.

- - -
- -
items -
-Initialisation option. A sequence of strings containing the initial items to be displayed - in the menu component. The default is ().

- - -
- -
labelmargin -
-Initialisation option. If the labelpos option is not None, this specifies the - distance between the label component and the rest of the - megawidget. The default is 0.

- - -
- -
labelpos -
-Initialisation option. Specifies where to place the label component. If not - None, it should be a concatenation of one or two of the - letters 'n', 's', 'e' and 'w'. The first letter - specifies on which side of the megawidget to place the label. - If a second letter is specified, it indicates where on that - side to place the label. For example, if labelpos is 'w', - the label is placed in the center of the left hand side; if - it is 'wn', the label is placed at the top of the left - hand side; if it is 'ws', the label is placed at the - bottom of the left hand side.

-

If None, a label component is not created. The default is None.

- - - -
- -
sticky -
-Initialisation option. The default is 'ew'.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Frame.

- - -
- -
label -
-If the labelpos option is not None, this component is - created as a text label for the megawidget. See the - labelpos option for details. Note that to set, for example, - the text option of the label, you need to use the label_text - component option. By default, this component is a Tkinter.Label.

- - -
- -
menu -
-The popup menu displayed when the menubutton is pressed. By default, this component is a Tkinter.Menu.

- - -
- -
menubutton -
-The menu button displaying the currently selected value. By default, this component is a Tkinter.Menubutton.

- - -
-
- -

Methods

-Only methods specific to this megawidget are described below. -For a description of its inherited methods, see the -manual for its base class -Pmw.MegaWidget. -

- -
getcurselection()
-Same as getvalue() method.

- - -
- -
getvalue()
-Return the currently selected value.

- - -
- -
index(index)
-Return the numerical index of the menu item corresponding to - index. This may be specified in any of the following forms:

-
name
Specifies the menu item labelled name.

- -
-
number
Specifies the menu item numerically, where 0 corresponds to - the first menu item.

- -
-
Pmw.END
Specifies the last menu item.

- -
-
Pmw.SELECT
Specifies the currently selected menu item.

- -
- - -
- -
invoke(index = Pmw.SELECT)
-Calling this method is the same as selecting the menu item - specified by index: the text displayed by the - menubutton component is updated and the function specified by - the command option is called. index may have any of the - forms accepted by the index() method. The value returned by - command is returned.

- - -
- -
setitems(items, index = None)
-Replace all the items in the menu component with those specified - by items, which must be a sequence of strings.

-

If index is not None, set the selected value to index, which - may have any of the forms accepted by the index() method.

- -

If index is None and the textvariable option of the - menubutton component is the empty string, then if - the previous selected value is one of the items, then do not - change the selection. If the previous selected value is no longer - in items, then set the selected value to the first value in - items. If items is empty, set the selected value to the empty - string.

- -

If index is None and the textvariable option of the - menubutton component is not the empty string, then do not set - the selected value. This assumes that the variable is already (or - will be) set to the desired value.

- - - -
- -
setvalue(text)
-Set the text displayed by the menubutton component to text.

- - -
-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-        # Create and pack the OptionMenu megawidgets.
-        # The first one has a textvariable.
-        self.var = Tkinter.StringVar()
-        self.var.set('steamed')
-        self.method_menu = Pmw.OptionMenu(parent,
-                labelpos = 'w',
-                label_text = 'Choose method:',
-                menubutton_textvariable = self.var,
-                items = ['baked', 'steamed', 'stir fried', 'boiled', 'raw'],
-                menubutton_width = 10,
-        )
-        self.method_menu.pack(anchor = 'w', padx = 10, pady = 10)
-
-        self.vege_menu = Pmw.OptionMenu (parent,
-                labelpos = 'w',
-                label_text = 'Choose vegetable:',
-                items = ('broccoli', 'peas', 'carrots', 'pumpkin'),
-                menubutton_width = 10,
-                command = self._printOrder,
-        )
-        self.vege_menu.pack(anchor = 'w', padx = 10, pady = 10)
-
-        self.direction_menu = Pmw.OptionMenu (parent,
-                labelpos = 'w',
-                label_text = 'Menu direction:',
-                items = ('flush', 'above', 'below', 'left', 'right'),
-                menubutton_width = 10,
-                command = self._changeDirection,
-        )
-        self.direction_menu.pack(anchor = 'w', padx = 10, pady = 10)
-
-        menus = (self.method_menu, self.vege_menu, self.direction_menu)
-        Pmw.alignlabels(menus)
-
-    def _printOrder(self, vege):
-        # Can use 'self.var.get()' instead of 'getcurselection()'.
-        print 'You have chosen %s %s.' % \
-            (self.method_menu.getcurselection(), vege)
-
-    def _changeDirection(self, direction):
-        for menu in (self.method_menu, self.vege_menu, self.direction_menu):
-            menu.configure(menubutton_direction = direction)
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 23 October 1998 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/PanedWidget.gif b/Pmw/Pmw_1_2/doc/PanedWidget.gif deleted file mode 100644 index eecbbf20..00000000 Binary files a/Pmw/Pmw_1_2/doc/PanedWidget.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/PanedWidget.html b/Pmw/Pmw_1_2/doc/PanedWidget.html deleted file mode 100644 index bcbb6630..00000000 --- a/Pmw/Pmw_1_2/doc/PanedWidget.html +++ /dev/null @@ -1,345 +0,0 @@ - - - - - - Pmw.PanedWidget reference manual - - - - -

Pmw.PanedWidget

- -
-
-

Name

-

Pmw.PanedWidget() - - frame subdivided into several resizable panes -

- - -
-

Inherits

-Pmw.MegaWidget
-
-

Description

-

- A paned widget is a container megawidget which manages a number of - resizable frames, known as panes. Each pane may act as the container for - other widgets. The user may interactively resize the panes by - dragging a small rectangle (the handle) or the line between the - panes (the separator). The panes may be arranged horizontally or - vertically. Each pane may have maximum and minimum limits of its - size.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
command -
-Specifies a function to be called whenever the size of any of the - panes changes. The function is called with a single argument, - being a list of the sizes of the panes, in order. For vertical - orientation, the size is the height of the panes. For - horizontal orientation, the size is the width of the panes. The default is None.

- - -
- -
handlesize -
-Initialisation option. Specifies the size in pixels of the square handle which appears on - the lines separating the panes. The default is 8.

- - -
- -
orient -
-Initialisation option. Specifies the orientation of the paned widget. This may be - 'horizontal' or 'vertical'. If 'vertical', the panes are - stacked above and below each other, otherwise the panes are laid - out side by side. The default is 'vertical'.

- - -
- -
separatorrelief -
-Initialisation option. Specifies the relief of the lines separating the panes. The default is 'sunken'.

- - -
- -
separatorthickness -
-Initialisation option. Specifies the thickness of the lines separating the panes. The default is 2.

- - -
-
-

Pane options

-

- Each pane has the following options. These may be set when - creating or configuring a pane. The value of each option may - be an integer, which specifies a pane size in pixels, or a - real number between 0.0 and 1.0, which specifies a pane size - proportional to the size of the entire paned widget.

- -
size
Specifies the initial size of the pane. The default is 0.

- -
-
min
Specifies the minimum size of the pane. The default is 0.

- -
-
max
Specifies the maximum size of the pane. The default is a - very large number.

-

- - -
- -
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Frame.

- - -
-
-

Dynamic components

-

- Frame, separator and handle components are created dynamically - by the add() and insert() methods. The components are of type - Tkinter.Frame and are created with component groups of - Frame, Separator and Handle respectively.

-

- - - -
- -

Methods

-Only methods specific to this megawidget are described below. -For a description of its inherited methods, see the -manual for its base class -Pmw.MegaWidget. -

- -
add(name, **kw)
-Add a pane to the end of the paned widget as a component named - name. This is equivalent to calling insert() with before - set to the current number of panes. The method returns the name - component widget.

- - -
- -
configurepane(name, **kw)
-Configure the pane specified by name, where name is either an - integer, specifying the index of the pane, or a string, specifying - the name of the pane. The keyword arguments specify the new - values for the options for the pane. These options are described - in the Pane options section.

- - -
- -
delete(name)
-Delete the pane specified by name, where name is either an - integer, specifying the index of the pane, or a string, specifying - the name of the pane.

-

If the pane deleted was not the only pane in the paned widget, - also delete the separator and handle components named - separator-n and handle-n, where n is the number of - panes remaining.

- - - -
- -
insert(name, before = 0, **kw)
-Add a pane to the paned widget as a component named name. The - pane is added just before the pane specified by before, where - before may be either an integer, specifying the index of the - pane, or a string, specifying the name of the pane. The keyword - arguments specify the initial values for the options for the new - pane. These options are described in the Pane options section. - To add a pane to the end of the paned widget, use add().

-

The new pane is created as a Tkinter.Frame component named name. - If this is not the only pane, a separator and handle are also - created as components named separator-n and handle-n, - where n is one less than the number of panes. The method - returns the name component widget.

- - - -
- -
move(name, newPos, newPosOffset = 0)
-Move the pane specified by name to the new position specified by - newPos. The first two arguments may be either an integer, - specifying the index of the pane, or a string, specifying the name - of the pane. If newPosOffset is specified, it is added to the - newPos index. For example, to move a horizontal pane one pane - to the left, specify the name or index of the pane for both name - and newPos and specify -1 for newPosOffset.

- - -
- -
pane(name)
-Return the Tkinter.Frame pane widget for the pane specified by - name, where name is either an integer, specifying the index of - the pane, or a string, specifying the name of the pane.

- - -
- -
panes()
-Return a list of the names of the panes, in display order.

- - -
- -
setnaturalsize()
-If oriented horizontally, set the width of the paned widget to the - sum of the requested widths of all panes and set the height to the - maximum requested height of all panes.

-

If oriented vertically, set the height of the paned widget to the - sum of the requested heights of all panes and set the width to the - maximum requested width of all panes.

- - - -
- -
updatelayout()
-Recalculate size and position of panes. This method must be - called after adding or deleting one or more panes. However it - does not need to be called when panes are first added to a newly - created paned widget, before it has been displayed.

- - -
-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-
-        # Create a main PanedWidget with a few panes.
-        self.pw = Pmw.PanedWidget(parent,
-                orient='vertical',
-                hull_borderwidth = 1,
-                hull_relief = 'sunken',
-                hull_width=300,
-                hull_height=400)
-        for self.numPanes in range(4):
-            if self.numPanes == 1:
-                name = 'Fixed size'
-                pane = self.pw.add(name, min = .1, max = .1)
-            else:
-                name = 'Pane ' + str(self.numPanes)
-                pane = self.pw.add(name, min = .1, size = .25)
-            label = Tkinter.Label(pane, text = name)
-            label.pack(side = 'left', expand = 1)
-            button = Tkinter.Button(pane, text = 'Delete',
-                    command = lambda s=self, n=name: s.deletePane(n))
-            button.pack(side = 'left', expand = 1)
-            # TODO: add buttons to invoke self.moveOneUp and self.moveOneUp.
-
-        self.pw.pack(expand = 1, fill='both')
-
-        buttonBox = Pmw.ButtonBox(parent)
-        buttonBox.pack(fill = 'x')
-        buttonBox.add('Add pane', command = self.addPane)   
-        buttonBox.add('Move pane', command = self.move)   
-        self.moveSrc = 0
-        self.moveNewPos = 1
-        self.moveBack = 0
-
-    def move(self):
-        numPanes = len(self.pw.panes())
-        if numPanes == 0:
-            print 'No panes to move!'
-            return
-
-        if self.moveSrc >= numPanes:
-            self.moveSrc = numPanes - 1
-        if self.moveNewPos >= numPanes:
-            self.moveNewPos = numPanes - 1
-        print 'Moving pane', self.moveSrc, 'to new position', self.moveNewPos
-        self.pw.move(self.moveSrc, self.moveNewPos)
-
-        self.moveSrc, self.moveNewPos = self.moveNewPos, self.moveSrc
-        if self.moveBack:
-            if self.moveNewPos == numPanes - 1:
-                self.moveNewPos = 0
-                if self.moveSrc == numPanes - 1:
-                    self.moveSrc = 0
-                else:
-                    self.moveSrc = self.moveSrc + 1
-            else:
-                self.moveNewPos = self.moveNewPos + 1
-        self.moveBack = not self.moveBack
-
-    def addPane(self):
-        self.numPanes = self.numPanes + 1
-        name = 'Pane ' + str(self.numPanes)
-        print 'Adding', name
-        pane = self.pw.add(name, min = .1, size = .25)
-        label = Tkinter.Label(pane, text = name)
-        label.pack(side = 'left', expand = 1)
-        button = Tkinter.Button(pane, text = 'Delete',
-                command = lambda s=self, n=name: s.deletePane(n))
-        button.pack(side = 'left', expand = 1)
-        self.pw.updatelayout()
-
-    def deletePane(self, name):
-        print 'Deleting', name
-        self.pw.delete(name)
-        self.pw.updatelayout()
-
-    def moveOneUp(self, name):
-        self.pw.move(name, name, -1)
-
-    def moveOneDown(self, name):
-        self.pw.move(name, name, 1)
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 14 April 2001 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/PmwFunctions.html b/Pmw/Pmw_1_2/doc/PmwFunctions.html deleted file mode 100644 index af22de8f..00000000 --- a/Pmw/Pmw_1_2/doc/PmwFunctions.html +++ /dev/null @@ -1,766 +0,0 @@ - - - - - - Pmw functions reference manual - - - - -

Pmw functions

- -
-
Pmw.aboutcontact(value)
-

- The value passed to this function is used to construct the text - displayed by Pmw.AboutDialog megawidgets created subsequently.

- -

- - -
-
Pmw.aboutcopyright(value)
-

- The value passed to this function is used to construct the text - displayed by Pmw.AboutDialog megawidgets created subsequently.

- -

- - -
-
Pmw.aboutversion(value)
-

- The value passed to this function is used to construct the text - displayed by Pmw.AboutDialog megawidgets created subsequently.

- -

- - -
-
Pmw.aligngrouptags(groups)
-

- This function takes a sequence of Pmw.Groups and adjusts the - vertical position of the tags in each group so that they all have - the height of the tallest tag. This can be used when groups are - positioned side-by-side but the natural height of the tags are - different because, for example, different fonts with different - sizes are used.

- -

- - -
-
Pmw.alignlabels(widgets, sticky = None)
-

- Adjust the size of the labels of all the widgets to be equal, so - that the body of each widget lines up vertically. This assumes - that each widget is a megawidget with a label component in - column 0 (ie, the labelpos option was set to 'w', 'wn' or - 'ws'). If sticky is set to a combination of 'n', 's', - 'e' and 'w', the label will be positioned within its cell - accordingly. For example to make labels right justified, set - sticky to 'e', 'ne' or 'se'.

- -

- - -
-
Pmw.alphabeticvalidator(text)
-

- Validator function for Pmw.EntryField alphabetic standard validator.

- -

- - -
-
Pmw.alphanumericvalidator(text)
-

- Validator function for Pmw.EntryField alphanumeric standard validator.

- -

- - -
-
Pmw.busycallback(command, updateFunction = None)
-

- Create a wrapper function which displays a busy cursor while - executing command and return the wrapper. When the wrapper - function is called, it first calls Pmw.showbusycursor(), then - the command (passing any arguments to it), then Pmw.hidebusycursor(). - The return value of command is returned from the wrapper.

- -

If updateFunction is specified, it is called just before the - call to Pmw.hidebusycursor(). This is intended to be the - Tkinter update() method, in which case it will clear any events - that may have occurred while command was executing. An example - of this usage is in the ShowBusy demonstration: run the - demonstration, click on the entry widget then click on the button - and type some characters while the busy cursor is displayed. No - characters should appear in the entry widget.

- -

Note that the Tkinter update() method should only be called when - it is known that it can be safely called. One case where a - problem has been found is when a filehandler has been created (on - a non-blocking Oracle database connection), but the filehandler - does not read from the connection. The connection is read (by a - call to the Oracle fetch function ofen) in a loop which also - contains a call to _tkinter.dooneevent(). If update() is - called from dooneevent() and there is data to be read on the - connection, then the filehandler will be called continuously, thus - hanging the application.

- -

- - -
-
Pmw.clearbusycursor()
-

- Unconditionally remove the event block and busy cursor from all - windows. This undoes all outstanding calls to - Pmw.showbusycursor().

- -

- - -
-
Pmw.datestringtojdn(text, format = 'ymd', separator = '/')
-

- Return the Julian Day Number corresponding to the date in text. - A Julian Day Number is defined as the number of days since 1 Jan 4713 - BC. The date must be specified as three integers separated by the - separator character. The integers must be in the order specified by - format, which must be a combination of 'd', 'm' and 'y' in - any order. These give the order of the day, month and year - fields. Examples of valid input are:

-
 'dmy':  31/01/99  31/1/1999  31/1/99
- 'mdy':  01/31/99  1/31/1999  1/31/99
- 'ymd':  99/01/31  1999/1/31  99/1/31
- - -

If the application's - pivot year (default 50) is not None and the year specified - in text has only one or two digits, then the year is - converted to a four digit year. If it is less than or equal to - the pivot year, then it is incremented by the application's - century value (default 2000). If it is more than the pivot year - then it is incremented by the century value less 100.

- -

The function Pmw.setyearpivot() can be used to change the - default values for the application's - pivot and century.

- -

- - -
-
Pmw.datevalidator(text, format = 'ymd', separator = '/')
-

- Validator function for Pmw.EntryField date standard validator.

- -

- - -
-
Pmw.displayerror(text)
-

- This is a general purpose method for displaying background errors - to the user. The errors would normally be programming errors and - may be caused by errors in Tk callbacks or functions called by other - asynchronous events.

- -

If the global error report file (set by calling - Pmw.reporterrorstofile()) is None, the error message `text` is - written to standard error and also shown in a text window. If - displayerror is called while previous error messages are being - displayed, the window is raised and the new error is queued. The - queued errors may be viewed by the user or ignored by dismissing - the window.

- -

If the global error report file is not None, `text` is written - to the file. file may be any object with a write() method, - such as sys.stderr.

- -

- - -
-
Pmw.drawarrow(canvas, color, direction, tag, baseOffset = 0.25, edgeOffset = 0.15)
-

- Draw a triangle in the Tkinter.Canvas canvas in the given - color. The value of direction may be 'up', 'down', - 'left' or 'right' and specifies which direction the arrow - should point. The values of baseOffset and edgeOffset specify - how far from the edges of the canvas the points of the triangles - are as a fraction of the size of the canvas.

- -

- - -
-
Pmw.forwardmethods(fromClass, toClass, toPart, exclude = ())
-

- Forward methods from one class to another.

- -

This function adds methods to the class fromClass. The names of - the methods added are the names of the methods of the class - toClass (and its base classes) except those which are already - defined by fromClass or are found in the exclude list. - Special methods with one or more leading or trailing underscores - are also excluded.

- -

When one of the added methods is called, the method of the same - name is called on an instance defined by toPart and the return - value passed back. If toPart is a string, then it specifies the - name of an attribute (not a component) of the fromClass - object. The class of this attribute should be toClass. If - toPart is not a string, it must be a function taking a - fromClass object and returning a toClass object.

- -

This function must be called outside of and after the definition - of fromClass.

- -

For example:

- -
class MyClass:
-    def __init__(self):
-        ...
-        self.__target = TargetClass()
-        ...
-
-    def foo(self):
-        pass
-
-    def findtarget(self):
-        return self.__target
-
-Pmw.forwardmethods(MyClass, TargetClass, '__target',
-    ['dangerous1', 'dangerous2'])
-
-# ...or...
-
-Pmw.forwardmethods(MyClass, TargetClass,
-    MyClass.findtarget, ['dangerous1', 'dangerous2'])
- -

In both cases, all TargetClass methods will be forwarded from - MyClass except for dangerous1, dangerous2, special methods like - __str__, and pre-existing methods like foo.

- -

- - -
-
Pmw.grabstacktopwindow()
-

- Return the window at the top of the grab stack (the window - currently with the grab) or None if the grab stack is empty (no - window has the grab). See also pushgrab().

- -

- - -
-
Pmw.hexadecimalvalidator(text)
-

- Validator function for Pmw.EntryField hexadecimal standard validator.

- -

- - -
-
Pmw.hidebusycursor(forceFocusRestore = 0)
-

- Undo one call to Pmw.showbusycursor(). If there are no - outstanding calls to Pmw.showbusycursor(), remove the event - block and busy cursor.

- -

If the focus window has not been changed since the corresponding - call to Pmw.showbusycursor(), or if forceFocusRestore is true, - then the focus is restored to that saved by Pmw.showbusycursor().

- -

- - -
-
Pmw.initialise(root = None, size = None, fontScheme = None, useTkOptionDb = 0, noBltBusy = 0, disableKeyboardWhileBusy = None)
-

- Initialise Pmw. This performs several functions:

-
  • Set up a trap in the Tkinter Toplevel constructor so that a - list of Toplevels can be maintained. A list of all Toplevel - windows needs to be kept so that Pmw.showbusycursor() can - create busy cursors for them.

    - -
  • -
  • Set up a trap in the Tkinter Toplevel and Frame destructors - so that Pmw is notified when these widgets are destroyed. - This allows Pmw to destroy megawidgets when their hull - widget is destroyed and to prune the list of Toplevels.

    - -
  • -
  • Modify Tkinter's CallWrapper class to improve the display of - errors which occur in callbacks. If an error occurs, the - new CallWrapper class calls Pmw.clearbusycursor() to - remove any outstanding busy cursors and calls - Pmw.displayerror() to display the error.

    - -
  • -
  • Using the window given by root, set the WM_DELETE_WINDOW - root window protocol to destroy the root window. This means - that the root window is destroyed if the window manager - deletes it. This is only done if the protocol has not been - set before the call to Pmw.initialise(). This protocol is - required if there is a modal dialog displayed and the window - manager deletes the root window. Otherwise the application - will not exit, even though there are no windows.

    - -
  • -
  • Set the base font size for the application to size. This - is used by Pmw.logicalfont() as the default point size for - fonts. If this is not given, the default is 14, except - under NT where it is 16. These are reasonable default - sizes for most screens, but for unusually high or low screen - resolutions, an appropriate size should be supplied. Note - that Tk's definition of point size, is somewhat - idiosyncratic.

    - -
  • -
  • Set the Tk option database for root according to - fontScheme. This changes the default fonts set by Tk. - fontScheme may be one of

    -
    None
    Do not change the Tk defaults.

    - -
    -
    'pmw1'
    If running under posix (Unix), set the default font to - be Helvetica with bold italic menus, italic scales and - a special balloon font 6 points smaller than the base - font size and with the 'pixel' field set to '12'. - For other operating systems (such as NT or Macintosh), - simply set the default font to be Helvetica. All - fonts are as returned by calls to Pmw.logicalfont().

    - -
    -
    'pmw2'
    This is the same as 'pmw1' except that under posix - the balloon font is 2 points smaller than the base - font size and the 'pixel' field is not set.

    - -
    -
    'default'
    This sets the default fonts using the Tk font naming - convention, rather than that returned by - Pmw.logicalfont(). The default font is bold - Helvetica. The font for entry widgets is Helvetica. - The font for text widgets is Courier The size of all - fonts is the application base font size as described - above.

    - -
    - -
  • -
  • If root is None, use the Tkinter default root window as the - root, if it has been created, or create a new Tk root window. - The initialise() method returns this root.

    - -
  • -
  • If useTkOptionDb is true, then, when a megawidget is - created, the Tk option database will be queried to get the - initial values of the options which have not been set in - the call to the constructor. The resource name used in the - query is the same as the option name and the resource class - is the option name with the first letter capitalised. If - useTkOptionDb is false, then options for newly created - megawidgets will be initialised to default values.

    - -
  • -
  • If noBltBusy is true, then Pmw.showbusycursor() will not - display a busy cursor, even if the BLT busy command is - present.

    - -
  • -
  • If disableKeyboardWhileBusy is false, then do not disable - keyboard input while displaying the busy cursor. Normally, - Pmw ignores keyboard input while displaying the busy cursor - by setting the focus for each toplevel window to the Blt - busy window. However, under NT, this may cause the toplevel - windows to be raised. If this is not acceptable, programs - running on NT can request show/hidebusycursor to not ignore - keyboard input by setting disableKeyboardWhileBusy to true - in Pmw.initialise().

    - -
- -

It is not absolutely necessary to call this function to be able to use - Pmw. However, some functionality will be lost. Most importantly, - Pmw megawidgets will not be notified when their hull widget is - destroyed. This may prevent the megawidget from cleaning up - timers which will try to access the widget, hence causing a - background error to occur.

- -

- - -
-
Pmw.installedversions(alpha = 0)
-

- If alpha is false, return the list of base versions of Pmw - that are currently installed and available for use. If alpha is - true, return the list of alpha versions.

- -

- - -
-
Pmw.integervalidator(text)
-

- Validator function for Pmw.EntryField integer standard validator.

- -

- - -
-
Pmw.jdntoymd(jdn, julian = -1, papal = 1)
-

- Return the year, month and day of the Julian Day Number jdn. If - julian is 1, then the date returned will be in the Julian - calendar. If julian is 0, then the date returned will be in - the modern calendar. If julian is -1, then which calendar to - use will be automatically determined by the value of jdn and - papal. If papal is true, then the date set by Pope Gregory - XIII's decree (4 October 1582) will be used as the last day to use - the Julian calendar. If papal is false, then the last day to - use the Julian calendar will be according to British-American - usage (2 September 1752).

- -

- - -
-
Pmw.logicalfont(name = 'Helvetica', sizeIncr = 0, **kw)
-

- Return the full name of a Tk font, being a hyphen-separated list - of font properties. The logical name of the font is given by - name and may be one of 'Helvetica', 'Times', 'Fixed', - 'Courier' or 'Typewriter'. Pmw uses this name to define the - default values of many of the font properties. The size of the - font is the base font size for the application specified in the - call to Pmw.initialise() increased or decreased by the value of - sizeIncr. The other properties of the font may be specified by - other named arguments. These may be 'registry', 'foundry', - 'family', 'weight', 'slant', 'width', 'style', - 'pixel', 'size', 'xres', 'yres', 'spacing', - 'avgwidth', 'charset' and 'encoding'.

- -

- - -
-
Pmw.logicalfontnames()
-

- Return the list of known logical font names that can be given - to Pmw.logicalfont().

- -

- - -
-
Pmw.numericvalidator(text)
-

- Validator function for Pmw.EntryField numeric standard validator.

- -

- - -
-
Pmw.popgrab(window)
-

- Remove window from the grab stack. If there are not more - windows in the grab stack, release the grab. Otherwise set the - grab and the focus to the next window in the grab stack. See also - pushgrab().

- -

- - -
-
Pmw.pushgrab(grabWindow, globalMode, deactivateFunction)
-

- The grab functions (pushgrab(), popgrab(), releasegrabs() - and grabstacktopwindow()) are an interface to the Tk grab - command which implements simple pointer and keyboard grabs. When - a grab is set for a particular window, Tk restricts all pointer - events to the grab window and its descendants in Tk's window - hierarchy. The functions are used by the activate() and - deactivate() methods to implement modal dialogs.

- -

Pmw maintains a stack of grabbed windows, where the window on the - top of the stack is the window currently with the grab. The grab - stack allows nested modal dialogs, where one modal dialog can be - activated while another modal dialog is activated. When the - second dialog is deactivated, the first dialog becomes active - again.

- -

Use pushgrab() to add grabWindow to the grab stack. This - releases the grab by the window currently on top of the stack (if - there is one) and gives the grab and focus to the grabWindow. - If globalMode is true, perform a global grab, otherwise perform - a local grab. The value of deactivateFunction specifies a - function to call (usually grabWindow.deactivate) if popgrab() is - called (usually from a deactivate() method) on a window which is - not at the top of the stack (that is, does not have the grab or - focus). For example, if a modal dialog is deleted by the window - manager or deactivated by a timer. In this case, all dialogs - above and including this one are deactivated, starting at the top - of the stack.

- -

For more information, see the Tk grab manual page.

- -

- - -
-
Pmw.realvalidator(text, separator = '.')
-

- Validator function for Pmw.EntryField real standard validator.

- -

- - -
-
Pmw.releasegrabs()
-

- Release grab and clear the grab stack. This should normally not - be used, use popgrab() instead. See also pushgrab().

- -

- - -
-
Pmw.reporterrorstofile(file = None)
-

- Sets the global error report file, which is initially None. See - Pmw.displayerror()

- -

- - -
-
Pmw.setalphaversions(*alpha_versions)
-

- Set the list of alpha versions of Pmw to use for this session to - the arguments. When searching for Pmw classes and functions, - these alpha versions will be searched, in the order given, before - the base version. This must be called before any other Pmw class - or function, except functions setting or querying versions.

- -

- - -
-
Pmw.setbusycursorattributes(window, **kw)
-

- Use the keyword arguments to set attributes controlling the effect - on window (which must be a Tkinter.Toplevel) of future calls - to Pmw.showbusycursor(). The attributes are:

- -
exclude
a boolean value which specifies whether the window - will be affected by calls to Pmw.showbusycursor(). If a window - is excluded, then the cursor will not be changed to a busy cursor - and events will still be delivered to the window. By default, - windows are affected by calls to Pmw.showbusycursor().

- -
-
cursorName
the name of the cursor to use when displaying the - busy cursor. If None, then the default cursor is used.

- -
-

- - -
-
Pmw.setgeometryanddeiconify(window, geom)
-

- Deiconify and raise the toplevel window and set its position and - size according to geom. This overcomes some problems with the - window flashing under X and correctly positions the window under - NT (caused by Tk bugs).

- -

- - -
-
Pmw.setversion(version)
-

- Set the version of Pmw to use for this session to version. If - Pmw.setversion() is not called, the latest installed version of - Pmw will be used. This must be called before any other Pmw class - or function, except functions setting or querying versions.

- -

- - -
-
Pmw.setyearpivot(pivot, century = None)
-

- Set the pivot year and century for the application's date - processing. These values are used in the datestringtojdn() - method, which is used by Pmw.Counter and Pmw.EntryField - and derived classes. The initial values of pivot and century - are 50 and 2000 repectively. Return a tuple containing the - old values of pivot and century.

- -

- - -
-
Pmw.showbusycursor()
-

- Block events to and display a busy cursor over all windows in this - application that are in the state 'normal' or 'iconic', except - those windows whose exclude busycursor attribute has been set to - true by a call to Pmw.setbusycursorattributes().

- -

If a window and its contents have just been created, - update_idletasks() may have to be called before - Pmw.showbusycursor() so that the window is mapped to the screen. - Windows created or deiconified after calling - Pmw.showbusycursor() will not be blocked.

- -

To unblock events and remove the busy cursor, use - Pmw.hidebusycursor(). Nested calls to Pmw.showbusycursor() - may be made. In this case, a matching number of calls to - Pmw.hidebusycursor() must be made before the event block and - busy cursor are removed.

- -

If the BLT extension to Tk is not present, this function has no - effect other than to save the value of the current focus window, - to be later restored by Pmw.hidebusycursor().

- -

- - -
-
Pmw.stringtoreal(text, separator = '.')
-

- Return the real number represented by text. This is similar to - string.atof() except that the character representing the decimal - point in text is given by separator.

- -

- - -
-
Pmw.timestringtoseconds(text, separator = ':')
-

- Return the number of seconds corresponding to the time in text. - The time must be specified as three integers separated by the - separator character and must be in the order hours, minutes and - seconds. The first number may be negative, indicating a negative - time.

- -

- - -
-
Pmw.timevalidator(text, separator = ':')
-

- Validator function for Pmw.EntryField time standard validator.

- -

- - -
-
Pmw.tracetk(root = None, on = 1, withStackTrace = 0, file = None)
-

- Print debugging trace of calls to, and callbacks from, the Tk - interpreter associated with the root window . If root is - None, use the Tkinter default root. If on is true, start - tracing, otherwise stop tracing. If withStackTrace is true, - print a python function call stacktrace after the trace for each - call to Tk. If file is None, print to standard error, - otherwise print to the file given by file.

- -

For each call to Tk, the Tk command and its options are printed as - a python tuple, followed by the return value of the command (if - not the empty string). For example:

- -
python executed:
-  button = Tkinter.Button()
-  button.configure(text = 'Hi')
-
-tracetk output:
-  CALL  TK> 1:  ('button', '.3662448') -> '.3662448'
-  CALL  TK> 1:  ('.3662448', 'configure', '-text', 'Hi')
- -

Some calls from python to Tk (such as update, tkwait, - invoke, etc) result in the execution of callbacks from Tk to - python. These python callbacks can then recursively call into Tk. - When displayed by tracetk(), these recursive calls are indented - proportionally to the depth of recursion. The depth is also - printed as a leading number. The return value of a call to Tk - which generated recursive calls is printed on a separate line at - the end of the recursion. For example:

- -
python executed:
-  def callback():
-      button.configure(text = 'Bye')
-      return 'Got me!'
-  button = Tkinter.Button()
-  button.configure(command = callback)
-  button.invoke()
- -
tracetk output:
-  CALL  TK> 1:  ('button', '.3587144') -> '.3587144'
-  CALL  TK> 1:  ('.3587144', 'configure', '-command', '3638368callback')
-  CALL  TK> 1:  ('.3587144', 'invoke')
-  CALLBACK> 2:    callback()
-  CALL  TK> 2:    ('.3587144', 'configure', '-text', 'Bye')
-  CALL RTN> 1:  -> 'Got me!'
- -

Pmw.initialise() must be called before tracetk() so that hooks - are put into the Tkinter CallWrapper class to trace callbacks from - Tk to python and also to handle recursive calls correctly.

- -

- - -
-
Pmw.version(alpha = 0)
-

- If alpha is false, return the base version of Pmw being used - for this session. If Pmw.setversion() has not been called, this - will be the latest installed version of Pmw. If alpha is true, - return the list of alpha versions of Pmw being used for this - session, in search order. If Pmw.setalphaversions() has not - been called, this will be the empty list.

- -

- - -
-
Pmw.ymdtojdn(year, month, day, julian = -1, papal = 1)
-

- Return the Julian Day Number corresponding to year, month and - day. See jdntoymd() for description of other arguments)

- -

- - -
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home - -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/PromptDialog.gif b/Pmw/Pmw_1_2/doc/PromptDialog.gif deleted file mode 100644 index b82205c9..00000000 Binary files a/Pmw/Pmw_1_2/doc/PromptDialog.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/PromptDialog.html b/Pmw/Pmw_1_2/doc/PromptDialog.html deleted file mode 100644 index f04b350b..00000000 --- a/Pmw/Pmw_1_2/doc/PromptDialog.html +++ /dev/null @@ -1,293 +0,0 @@ - - - - - - Pmw.PromptDialog reference manual - - - - -

Pmw.PromptDialog

- -
-
-

Name

-

Pmw.PromptDialog() - - selection dialog displaying an entry field -

- - -
-

Inherits

-Pmw.Dialog
-
-

Description

-

- The prompt dialog is a dialog window which displays an entry field - which can be used to prompt the user for a value.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
activatecommand -
-If this is callable, it will be called whenever the megawidget is - activated by a call to activate(). The default is None.

- - -
- -
borderx -
-Initialisation option. The padding to the left and right of the entry field. The default is 20.

- - -
- -
bordery -
-Initialisation option. The padding above and below the entry field. The default is 20.

- - -
- -
buttonboxpos -
-Initialisation option. Specifies on which side of the dialog window to place the button - box. Must be one of 'n', 's', 'e' or 'w'. The default is 's'.

- - -
- -
buttons -
-This must be a tuple or a list and specifies the names on the - buttons in the button box. The default is ('OK',).

- - -
- -
command -
-Specifies a function to call whenever a button in the button box - is invoked or the window is deleted by the window manager. The - function is called with a single argument, which is the name of - the button which was invoked, or None if the window was deleted - by the window manager.

-

If the value of command is not callable, the default behaviour - is to deactivate the window if it is active, or withdraw the - window if it is not active. If it is deactivated, deactivate() - is called with the button name or None as described above. The default is None.

- - - -
- -
deactivatecommand -
-If this is callable, it will be called whenever the megawidget is - deactivated by a call to deactivate(). The default is None.

- - -
- -
defaultbutton -
-Specifies the default button in the button box. If the <Return> - key is hit when the dialog has focus, the default button will be - invoked. If defaultbutton is None, there will be no default - button and hitting the <Return> key will have no effect. The default is None.

- - -
- -
master -
-This is used by the activate() method to control whether the - window is made transient during modal dialogs. See the - activate() method. The default is 'parent'.

- - -
- -
separatorwidth -
-Initialisation option. If this is greater than 0, a separator line with the specified - width will be created between the button box and the child site, - as a component named separator. Since the default border of the - button box and child site is raised, this option does not - usually need to be set for there to be a visual separation between - the button box and child site. The default is 0.

- - -
- -
title -
-This is the title that the window manager displays in the title - bar of the window. The default is None.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
buttonbox -
-This is the button box containing the buttons for the dialog. By - default it is created with the options - (hull_borderwidth = 1, hull_relief = 'raised'). By default, this component is a Pmw.ButtonBox.

- - -
- -
dialogchildsite -
-This is the child site for the dialog, which may be used to - specialise the megawidget by creating other widgets within it. By - default it is created with the options - (borderwidth = 1, relief = 'raised'). By default, this component is a Tkinter.Frame.

- - -
- -
entryfield -
-The entry field for the user to enter a value. By default, this component is a Pmw.EntryField.

- - -
- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Toplevel.

- - -
- -
separator -
-If the separatorwidth initialisation option is non-zero, the - separator component is the line dividing the area between the - button box and the child site. By default, this component is a Tkinter.Frame.

- - -
-
-

Component aliases

-Sub-components of components of this megawidget -may be accessed via the following aliases.

-
entry -
-Alias for entryfield_entry. -
-
label -
-Alias for entryfield_label. -
-
- -

Methods

-Only methods specific to this megawidget are described below. -For a description of its inherited methods, see the -manual for its base class -Pmw.Dialog. -In addition, methods from the -Pmw.EntryField class -are forwarded by this megawidget to the -entryfield component. -

- -
deleteentry(first, last = None)
-Delete text from the entry field's entry widget. An alias for - component('entry').delete().

- - -
- -
indexentry(index)
-An alias for component('entry').index().

- - -
- -
insertentry(index, text)
-Insert text into the entry field's entry widget. An alias for - component('entry').insert().

- - -
-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-        # Create the dialog to prompt for the password.
-        self.dialog = Pmw.PromptDialog(parent,
-            title = 'Password',
-            label_text = 'Password:',
-            entryfield_labelpos = 'n',
-            entry_show = '*',
-            defaultbutton = 0,
-            buttons = ('OK', 'Cancel'),
-            command = self.execute)
-        self.dialog.withdraw()
-
-        # Create the confirmation dialog.
-        self.confirm = Pmw.MessageDialog(
-            title = 'Are you sure?',
-            message_text = 'Are you really sure?',
-            defaultbutton = 0,
-            buttons = ('OK', 'Cancel'))
-        self.confirm.withdraw()
-
-        # Create button to launch the dialog.
-        w = Tkinter.Button(parent, text = 'Show prompt dialog',
-                command = self.dialog.activate)
-        w.pack(padx = 8, pady = 8)
-
-    def execute(self, result):
-        if result is None or result == 'Cancel':
-            print 'Password prompt cancelled'
-            self.dialog.deactivate(result)
-        else:
-            result = self.confirm.activate()
-            if result == 'OK':
-                print 'Password entered ' + self.dialog.get()
-                self.dialog.deactivate()
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 18 May 2002 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/RadioSelect.gif b/Pmw/Pmw_1_2/doc/RadioSelect.gif deleted file mode 100644 index 026a1397..00000000 Binary files a/Pmw/Pmw_1_2/doc/RadioSelect.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/RadioSelect.html b/Pmw/Pmw_1_2/doc/RadioSelect.html deleted file mode 100644 index bdf871c4..00000000 --- a/Pmw/Pmw_1_2/doc/RadioSelect.html +++ /dev/null @@ -1,405 +0,0 @@ - - - - - - Pmw.RadioSelect reference manual - - - - -

Pmw.RadioSelect

- -
-
-

Name

-

Pmw.RadioSelect() - - a set of buttons, some of which may be selected -

- - -
-

Inherits

-Pmw.MegaWidget
-
-

Description

-

- A radio select is a container megawidget which manages a number of - buttons. The buttons may be laid out either horizontally or - vertically. In single selection mode, only one button may be - selected at any one time. In multiple selection mode, several - buttons may be selected at the same time and clicking on a - selected button will deselect it.

- -

The buttons displayed can be either standard buttons, radio - buttons or check buttons. When selected, standard buttons are - displayed sunken and radio and check buttons are displayed with - the appropriate indicator color and relief.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
buttontype -
-Initialisation option. Specifies the default type of buttons created by the add() - method. If 'button', the default type is Tkinter.Button. If - 'radiobutton', the default type is Tkinter.Radiobutton. If - 'checkbutton', the default type is Tkinter.Checkbutton.

-

If 'radiobutton', single selection mode is automatically set. - If 'checkbutton', multiple selection mode is automatically set. The default is 'button'.

- - - -
- -
command -
-Specifies a function to call when one of the buttons is clicked on - or when invoke() is called.

-

In single selection mode, the function is called with a single - argument, which is the name of the selected button.

- -

In multiple selection mode, the function is called with the first - argument being the name of the button and the second argument - being true if the button is now selected or false if it is now - deselected. The default is None.

- - - -
- -
labelmargin -
-Initialisation option. If the labelpos option is not None, this specifies the - distance between the label component and the rest of the - megawidget. The default is 0.

- - -
- -
labelpos -
-Initialisation option. Specifies where to place the label component. If not - None, it should be a concatenation of one or two of the - letters 'n', 's', 'e' and 'w'. The first letter - specifies on which side of the megawidget to place the label. - If a second letter is specified, it indicates where on that - side to place the label. For example, if labelpos is 'w', - the label is placed in the center of the left hand side; if - it is 'wn', the label is placed at the top of the left - hand side; if it is 'ws', the label is placed at the - bottom of the left hand side.

-

If None, a label component is not created. The default is None.

- - - -
- -
orient -
-Initialisation option. Specifies the direction in which the buttons are laid out. This - may be 'horizontal' or 'vertical'. The default is 'horizontal'.

- - -
- -
padx -
-Initialisation option. Specifies a padding distance to leave between each button in the x - direction and also between the buttons and the outer edge of the - radio select. The default is 5.

- - -
- -
pady -
-Initialisation option. Specifies a padding distance to leave between each button in the y - direction and also between the buttons and the outer edge of the - radio select. The default is 5.

- - -
- -
selectmode -
-Initialisation option. Specifies the selection mode: whether a single button or multiple - buttons can be selected at one time. If 'single', clicking on - an unselected button selects it and deselects all other buttons. - If 'multiple', clicking on an unselected button selects it and - clicking on a selected button deselects it. This option is - ignored if buttontype is 'radiobutton' or 'checkbutton'. The default is 'single'.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
frame -
-If the label component has been created (that is, the labelpos - option is not None), the frame component is created to act as - the container of the buttons created by the add() method. If - there is no label component, then no frame component is - created and the hull component acts as the container. By default, this component is a Tkinter.Frame.

- - -
- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Frame.

- - -
- -
label -
-If the labelpos option is not None, this component is - created as a text label for the megawidget. See the - labelpos option for details. Note that to set, for example, - the text option of the label, you need to use the label_text - component option. By default, this component is a Tkinter.Label.

- - -
-
-

Dynamic components

-

- Button components are created dynamically by the add() - method. The default type of the buttons depends on the value - of the buttontype option.

- -

Button components are created with a component group of Button.

-

- - - -
- -

Methods

-Only methods specific to this megawidget are described below. -For a description of its inherited methods, see the -manual for its base class -Pmw.MegaWidget. -

- -
add(componentName, **kw)
-Add a button to the end of the radio select as a component - named componentName. with a default type as specified by - buttontype. Any keyword arguments present (except command) - will be passed to the constructor when creating the button. If - the text keyword argument is not given, the text option of the - button defaults to componentName. The method returns the - component widget.

- - -
- -
button(buttonIndex)
-Return the button specified by buttonIndex, which may have any - of the forms accepted by the index() method.

- - -
- -
deleteall()
-Delete all buttons and clear the current selection.

- - -
- -
getcurselection()
-Same as getvalue() method.

- - -
- -
getvalue()
-In single selection mode, return the name of the currently - selected button, or None if no buttons have been selected yet.

-

In multiple selection mode, return a list of the names of the - currently selected buttons.

- - - -
- -
index(index)
-Return the numerical index of the button corresponding to index. - This may be specified in any of the following forms:

-
name
Specifies the button named name.

- -
-
number
Specifies the button numerically, where 0 corresponds to - the left (or top) button.

- -
-
Pmw.END
Specifies the right (or bottom) button.

- -
- - -
- -
invoke(index)
-Calling this method is the same as clicking on the button - specified by index: the buttons are displayed selected or - deselected according to the selection mode and command is - called. index may have any of the forms accepted by the - index() method. The value returned by command is returned.

- - -
- -
numbuttons()
-Return the number of buttons in the radio select.

- - -
- -
setvalue(textOrList)
-Set the current selection for the radio select to textOrList, - but do not invoke command.

-

In single selection mode, select only the button specified by the - string textOrList.

- -

In multiple selection mode, select only the buttons specified by - the list textOrList.

- - - -
-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-        # Create and pack a horizontal RadioSelect widget.
-        horiz = Pmw.RadioSelect(parent,
-                labelpos = 'w',
-                command = self.callback,
-                label_text = 'Horizontal',
-                frame_borderwidth = 2,
-                frame_relief = 'ridge'
-        )
-        horiz.pack(fill = 'x', padx = 10, pady = 10)
-
-        # Add some buttons to the horizontal RadioSelect.
-        for text in ('Fruit', 'Vegetables', 'Cereals', 'Legumes'):
-            horiz.add(text)
-        horiz.invoke('Cereals')
-
-        # Create and pack a multiple selection RadioSelect widget.
-        self.multiple = Pmw.RadioSelect(parent,
-                labelpos = 'w',
-                command = self.multcallback,
-                label_text = 'Multiple\nselection',
-                frame_borderwidth = 2,
-                frame_relief = 'ridge',
-                selectmode = 'multiple',
-        )
-        self.multiple.pack(fill = 'x', padx = 10)
-
-        # Add some buttons to the multiple selection RadioSelect.
-        for text in ('Apricots', 'Eggplant', 'Rice', 'Lentils'):
-            self.multiple.add(text)
-        self.multiple.invoke('Rice')
-
-        # Create and pack a vertical RadioSelect widget, with checkbuttons.
-        self.checkbuttons = Pmw.RadioSelect(parent,
-                buttontype = 'checkbutton',
-                orient = 'vertical',
-                labelpos = 'w',
-                command = self.checkbuttoncallback,
-                label_text = 'Vertical,\nusing\ncheckbuttons',
-                hull_borderwidth = 2,
-                hull_relief = 'ridge',
-        )
-        self.checkbuttons.pack(side = 'left', expand = 1, padx = 10, pady = 10)
-
-        # Add some buttons to the checkbutton RadioSelect.
-        for text in ('Male', 'Female'):
-            self.checkbuttons.add(text)
-        self.checkbuttons.invoke('Male')
-        self.checkbuttons.invoke('Female')
-
-        # Create and pack a RadioSelect widget, with radiobuttons.
-        radiobuttons = Pmw.RadioSelect(parent,
-                buttontype = 'radiobutton',
-                orient = 'vertical',
-                labelpos = 'w',
-                command = self.callback,
-                label_text = 'Vertical,\nusing\nradiobuttons',
-                hull_borderwidth = 2,
-                hull_relief = 'ridge',
-        )
-        radiobuttons.pack(side = 'left', expand = 1, padx = 10, pady = 10)
-
-        # Add some buttons to the radiobutton RadioSelect.
-        for text in ('Male', 'Female', 'Both', 'Neither'):
-            radiobuttons.add(text)
-        radiobuttons.invoke('Both')
-
-    def callback(self, tag):
-        # This is called whenever the user clicks on a button
-        # in a single select RadioSelect widget.
-        print 'Button', tag, 'was pressed.'
-
-    def multcallback(self, tag, state):
-        # This is called whenever the user clicks on a button
-        # in the multiple select RadioSelect widget.
-        if state:
-           action = 'pressed.'
-        else:
-           action = 'released.'
-
-        print 'Button', tag, 'was', action, \
-                'Selection:', self.multiple.getcurselection()
-           
-    def checkbuttoncallback(self, tag, state):
-        # This is called whenever the user clicks on a button
-        # in the checkbutton RadioSelect widget.
-        if state:
-           action = 'pressed.'
-        else:
-           action = 'released.'
-
-        print 'Button', tag, 'was', action, \
-                'Selection:', self.checkbuttons.getcurselection()
-           
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 6 June 2002 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/ScrolledCanvas.gif b/Pmw/Pmw_1_2/doc/ScrolledCanvas.gif deleted file mode 100644 index da7941ae..00000000 Binary files a/Pmw/Pmw_1_2/doc/ScrolledCanvas.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/ScrolledCanvas.html b/Pmw/Pmw_1_2/doc/ScrolledCanvas.html deleted file mode 100644 index f3ebd216..00000000 --- a/Pmw/Pmw_1_2/doc/ScrolledCanvas.html +++ /dev/null @@ -1,352 +0,0 @@ - - - - - - Pmw.ScrolledCanvas reference manual - - - - -

Pmw.ScrolledCanvas

- -
-
-

Name

-

Pmw.ScrolledCanvas() - - canvas with optional scrollbars -

- - -
-

Inherits

-Pmw.MegaWidget
-
-

Description

-

- A scrolled canvas consists of a standard canvas widget with optional - scrollbars which can be used to scroll the canvas. The scrollbars - can be dynamic, which means that a scrollbar will only be - displayed if it is necessary, that is, if the scrollregion of the - canvas is larger than the canvas.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
borderframe -
-Initialisation option. If true, the borderframe component will be created. The default is 0.

- - -
- -
canvasmargin -
-Initialisation option. The margin around the items in the canvas. Used by the - resizescrollregion() method. The default is 0.

- - -
- -
hscrollmode -
-The horizontal scroll mode. If 'none', the horizontal scrollbar - will never be displayed. If 'static', the scrollbar will always - be displayed. If 'dynamic', the scrollbar will be displayed - only if necessary. The default is 'dynamic'.

- - -
- -
labelmargin -
-Initialisation option. If the labelpos option is not None, this specifies the - distance between the label component and the rest of the - megawidget. The default is 0.

- - -
- -
labelpos -
-Initialisation option. Specifies where to place the label component. If not - None, it should be a concatenation of one or two of the - letters 'n', 's', 'e' and 'w'. The first letter - specifies on which side of the megawidget to place the label. - If a second letter is specified, it indicates where on that - side to place the label. For example, if labelpos is 'w', - the label is placed in the center of the left hand side; if - it is 'wn', the label is placed at the top of the left - hand side; if it is 'ws', the label is placed at the - bottom of the left hand side.

-

If None, a label component is not created. The default is None.

- - - -
- -
scrollmargin -
-Initialisation option. The distance between the scrollbars and the enclosing canvas - widget. The default is 2.

- - -
- -
usehullsize -
-Initialisation option. If true, the size of the megawidget is determined solely by the - width and height options of the hull component.

-

Otherwise, the size of the megawidget is determined by the width - and height of the canvas component, along with the size and/or - existence of the other components, such as the label, the - scrollbars and the scrollmargin option. All these affect the - overall size of the megawidget. The default is 0.

- - - -
- -
vscrollmode -
-The vertical scroll mode. If 'none', the vertical scrollbar - will never be displayed. If 'static', the scrollbar will always - be displayed. If 'dynamic', the scrollbar will be displayed - only if necessary. The default is 'dynamic'.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
borderframe -
-A frame widget which snuggly fits around the canvas, to give the - appearance of a canvas border. It is created with a border so - that the canvas, which is created without a border, looks like it - has a border. By default, this component is a Tkinter.Frame.

- - -
- -
canvas -
-The canvas widget which is scrolled by the scrollbars. If the - borderframe option is true, this is created with a borderwidth - of 0 to overcome a known problem with canvas widgets: if a - widget inside a canvas extends across one of the edges of the - canvas, then the widget obscures the border of the canvas. - Therefore, if the canvas has no border, then this overlapping does - not occur. By default, this component is a Tkinter.Canvas.

- - -
- -
horizscrollbar -
-The horizontal scrollbar. By default, this component is a Tkinter.Scrollbar. Its component group is Scrollbar.

- - -
- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Frame.

- - -
- -
label -
-If the labelpos option is not None, this component is - created as a text label for the megawidget. See the - labelpos option for details. Note that to set, for example, - the text option of the label, you need to use the label_text - component option. By default, this component is a Tkinter.Label.

- - -
- -
vertscrollbar -
-The vertical scrollbar. By default, this component is a Tkinter.Scrollbar. Its component group is Scrollbar.

- - -
-
- -

Methods

-Only methods specific to this megawidget are described below. -For a description of its inherited methods, see the -manual for its base class -Pmw.MegaWidget. -In addition, methods from the -Tkinter.Canvas class -are forwarded by this megawidget to the -canvas component. -

- -
bbox(*args)
-This method is explicitly forwarded to the canvas component's - bbox() method. Without this explicit forwarding, the bbox() - method (aliased to grid_bbox()) of the hull would be invoked, - which is probably not what the programmer intended.

- - -
- -
interior()
-Return the canvas widget within which the programmer should create - graphical items and child widgets. This is the same as - component('canvas').

- - -
- -
resizescrollregion()
-Resize the scrollregion of the canvas component to be the - bounding box covering all the items in the canvas plus a margin on - all sides, as specified by the canvasmargin option.

- - -
-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-        # Create the ScrolledCanvas.
-        self.sc = Pmw.ScrolledCanvas(parent,
-                borderframe = 1,
-                labelpos = 'n',
-                label_text = 'ScrolledCanvas',
-                usehullsize = 1,
-                hull_width = 400,
-                hull_height = 300,
-        )
-
-        # Create a group widget to contain the scrollmode options.
-        w = Pmw.Group(parent, tag_text='Scroll mode')
-        w.pack(side = 'bottom', padx = 5, pady = 5)
-
-        hmode = Pmw.OptionMenu(w.interior(),
-                labelpos = 'w',
-                label_text = 'Horizontal:',
-                items = ['none', 'static', 'dynamic'],
-                command = self.sethscrollmode,
-                menubutton_width = 8,
-        )
-        hmode.pack(side = 'left', padx = 5, pady = 5)
-        hmode.invoke('dynamic')
-
-        vmode = Pmw.OptionMenu(w.interior(),
-                labelpos = 'w',
-                label_text = 'Vertical:',
-                items = ['none', 'static', 'dynamic'],
-                command = self.setvscrollmode,
-                menubutton_width = 8,
-        )
-        vmode.pack(side = 'left', padx = 5, pady = 5)
-        vmode.invoke('dynamic')
-
-        buttonBox = Pmw.ButtonBox(parent)
-        buttonBox.pack(side = 'bottom')
-        buttonBox.add('yview', text = 'Show\nyview', command = self.showYView)
-        buttonBox.add('scroll', text = 'Page\ndown', command = self.pageDown)
-        buttonBox.add('center', text = 'Center', command = self.centerPage)
-
-        # Pack this last so that the buttons do not get shrunk when
-        # the window is resized.
-        self.sc.pack(padx = 5, pady = 5, fill = 'both', expand = 1)
-
-        self.sc.component('canvas').bind('<1>', self.addcircle)
-
-        testEntry = Tkinter.Entry(parent)
-        self.sc.create_line(20, 20, 100, 100)
-        self.sc.create_oval(100, 100, 200, 200, fill = 'green')
-        self.sc.create_text(100, 20, anchor = 'nw',
-                text = 'Click in the canvas\nto draw ovals',
-                font = testEntry.cget('font'))
-        button = Tkinter.Button(self.sc.interior(),
-                text = 'Hello,\nWorld!\nThis\nis\na\nbutton.')
-        self.sc.create_window(200, 200,
-                anchor='nw',
-                window = button)
-
-        # Set the scroll region of the canvas to include all the items
-        # just created.
-        self.sc.resizescrollregion()
-
-        self.colours = ('red', 'green', 'blue', 'yellow', 'cyan', 'magenta',
-                'black', 'white')
-        self.oval_count = 0
-        self.rand = 12345
-
-    def sethscrollmode(self, tag):
-        self.sc.configure(hscrollmode = tag)
-
-    def setvscrollmode(self, tag):
-        self.sc.configure(vscrollmode = tag)
-
-    def addcircle(self, event):
-        x = self.sc.canvasx(event.x)
-        y = self.sc.canvasy(event.y)
-        width = 10 + self.random() % 100
-        height = 10 + self.random() % 100
-        self.sc.create_oval(
-            x - width, y - height, x + width, y + height,
-            fill = self.colours[self.oval_count])
-        self.oval_count = (self.oval_count + 1) % len(self.colours)
-        self.sc.resizescrollregion()
-
-    # Simple random number generator.
-    def random(self):
-        self.rand = (self.rand * 125) % 2796203
-        return self.rand
-
-    def showYView(self):
-        print self.sc.yview()
-
-    def pageDown(self):
-        self.sc.yview('scroll', 1, 'page')
-
-    def centerPage(self):
-        top, bottom = self.sc.yview()
-        size = bottom - top
-        middle = 0.5 - size / 2
-        self.sc.yview('moveto', middle)
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 20 September 1998 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/ScrolledField.gif b/Pmw/Pmw_1_2/doc/ScrolledField.gif deleted file mode 100644 index d1942e3d..00000000 Binary files a/Pmw/Pmw_1_2/doc/ScrolledField.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/ScrolledField.html b/Pmw/Pmw_1_2/doc/ScrolledField.html deleted file mode 100644 index 4c28cbc4..00000000 --- a/Pmw/Pmw_1_2/doc/ScrolledField.html +++ /dev/null @@ -1,187 +0,0 @@ - - - - - - Pmw.ScrolledField reference manual - - - - -

Pmw.ScrolledField

- -
-
-

Name

-

Pmw.ScrolledField() - - single line scrollable output field -

- - -
-

Inherits

-Pmw.MegaWidget
-
-

Description

-

- A scrolled field displays a single line of text. If the text is - too wide to display in the megawidget it can be scrolled to the - left and right by the user by dragging with the middle mouse - button. The text is also selectable by clicking or dragging with - the left mouse button.

- -

It can be used instead of a Tkinter.Label widget when displaying - text of unknown width such as application status messages.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
labelmargin -
-Initialisation option. If the labelpos option is not None, this specifies the - distance between the label component and the rest of the - megawidget. The default is 0.

- - -
- -
labelpos -
-Initialisation option. Specifies where to place the label component. If not - None, it should be a concatenation of one or two of the - letters 'n', 's', 'e' and 'w'. The first letter - specifies on which side of the megawidget to place the label. - If a second letter is specified, it indicates where on that - side to place the label. For example, if labelpos is 'w', - the label is placed in the center of the left hand side; if - it is 'wn', the label is placed at the top of the left - hand side; if it is 'ws', the label is placed at the - bottom of the left hand side.

-

If None, a label component is not created. The default is None.

- - - -
- -
sticky -
-Initialisation option. The default is 'ew'.

- - -
- -
text -
-Specifies the text to display in the scrolled field. The default is ''.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
entry -
-This is used to display the text and allows the user to scroll and - select the text. The state of this component is set to - 'readonly' (or 'disabled' in earlier versions of Tcl/Tk which do - not support 'readonly'), so that the user is unable to modify the text. By default, this component is a Tkinter.Entry.

- - -
- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Frame.

- - -
- -
label -
-If the labelpos option is not None, this component is - created as a text label for the megawidget. See the - labelpos option for details. Note that to set, for example, - the text option of the label, you need to use the label_text - component option. By default, this component is a Tkinter.Label.

- - -
-
- -

Methods

-This megawidget has no methods of its own. -For a description of its inherited methods, see the -manual for its base class -Pmw.MegaWidget. -In addition, methods from the -Tkinter.Entry class -are forwarded by this megawidget to the -entry component. -

-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-        # Create and pack the ScrolledField.
-        self._field = Pmw.ScrolledField(parent, entry_width = 30,
-                entry_relief='groove', labelpos = 'n',
-                label_text = 'Scroll the field using the\nmiddle mouse button')
-        self._field.pack(fill = 'x', expand = 1, padx = 10, pady = 10)
-
-        # Create and pack a button to change the ScrolledField.
-        self._button = Tkinter.Button(parent, text = 'Change field',
-                command = self.execute)
-        self._button.pack(padx = 10, pady = 10)
-
-        self._index = 0
-        self.execute()
-
-    def execute(self):
-        self._field.configure(text = lines[self._index % len(lines)])
-        self._index = self._index + 1
-
-lines = (
-  'Alice was beginning to get very tired of sitting by her sister',
-  'on the bank, and of having nothing to do:  once or twice she had',
-  'peeped into the book her sister was reading, but it had no',
-  'pictures or conversations in it, "and what is the use of a book,"',
-  'thought Alice "without pictures or conversation?"',
-  'Alice\'s Adventures in Wonderland',
-  'Lewis Carroll',
-)
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 23 August 1998 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/ScrolledFrame.gif b/Pmw/Pmw_1_2/doc/ScrolledFrame.gif deleted file mode 100644 index 089a201e..00000000 Binary files a/Pmw/Pmw_1_2/doc/ScrolledFrame.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/ScrolledFrame.html b/Pmw/Pmw_1_2/doc/ScrolledFrame.html deleted file mode 100644 index 5cfe3b3b..00000000 --- a/Pmw/Pmw_1_2/doc/ScrolledFrame.html +++ /dev/null @@ -1,479 +0,0 @@ - - - - - - Pmw.ScrolledFrame reference manual - - - - -

Pmw.ScrolledFrame

- -
-
-

Name

-

Pmw.ScrolledFrame() - - frame with optional scrollbars -

- - -
-

Inherits

-Pmw.MegaWidget
-
-

Description

-

- A scrolled frame consists of a scrollable interior frame within a - clipping frame. The programmer can create other widgets within - the interior frame. If the frame becomes larger than the - surrounding clipping frame, the user can position the frame using - the horizontal and vertical scrollbars.

- -

The scrollbars can be dynamic, which means that a scrollbar will - only be displayed if it is necessary. That is, if the frame is - smaller than the surrounding clipping frame, the scrollbar will be - hidden.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
borderframe -
-Initialisation option. If true, the borderframe component will be created. The default is 1.

- - -
- -
horizflex -
-Specifies how the width of the scrollable interior frame should be - resized relative to the clipping frame.

-

If 'fixed', the interior frame is set to the natural width, as - requested by the child widgets of the frame. If 'expand' and - the requested width of the interior frame is less than the width - of the clipping frame, the interior frame expands to fill the - clipping frame. If 'shrink' and the requested width of the - interior frame is more than the width of the clipping frame, the - interior frame shrinks to the width of the clipping frame. If - 'elastic', the width of the interior frame is always set to the - width of the clipping frame. The default is 'fixed'.

- - - -
- -
horizfraction -
-Initialisation option. The fraction of the width of the clipper frame to scroll the - interior frame when the user clicks on the horizontal scrollbar - arrows. The default is 0.05.

- - -
- -
hscrollmode -
-The horizontal scroll mode. If 'none', the horizontal scrollbar - will never be displayed. If 'static', the scrollbar will always - be displayed. If 'dynamic', the scrollbar will be displayed - only if necessary. The default is 'dynamic'.

- - -
- -
labelmargin -
-Initialisation option. If the labelpos option is not None, this specifies the - distance between the label component and the rest of the - megawidget. The default is 0.

- - -
- -
labelpos -
-Initialisation option. Specifies where to place the label component. If not - None, it should be a concatenation of one or two of the - letters 'n', 's', 'e' and 'w'. The first letter - specifies on which side of the megawidget to place the label. - If a second letter is specified, it indicates where on that - side to place the label. For example, if labelpos is 'w', - the label is placed in the center of the left hand side; if - it is 'wn', the label is placed at the top of the left - hand side; if it is 'ws', the label is placed at the - bottom of the left hand side.

-

If None, a label component is not created. The default is None.

- - - -
- -
scrollmargin -
-Initialisation option. The distance between the scrollbars and the clipping frame. The default is 2.

- - -
- -
usehullsize -
-Initialisation option. If true, the size of the megawidget is determined solely by the - width and height options of the hull component.

-

Otherwise, the size of the megawidget is determined by the width - and height of the clipper component, along with the size and/or - existence of the other components, such as the label, the - scrollbars and the scrollmargin option. All these affect the - overall size of the megawidget. The default is 0.

- - - -
- -
vertflex -
-Specifies how the height of the scrollable interior frame should - be resized relative to the clipping frame.

-

If 'fixed', the interior frame is set to the natural height, - as requested by the child widgets of the frame. If 'expand' and - the requested height of the interior frame is less than the height - of the clipping frame, the interior frame expands to fill the - clipping frame. If 'shrink' and the requested height of the - interior frame is more than the height of the clipping frame, the - interior frame shrinks to the height of the clipping frame. If - 'elastic', the height of the interior frame is always set to the - height of the clipping frame. The default is 'fixed'.

- - - -
- -
vertfraction -
-Initialisation option. The fraction of the height of the clipper frame to scroll the - interior frame when the user clicks on the vertical scrollbar - arrows. The default is 0.05.

- - -
- -
vscrollmode -
-The vertical scroll mode. If 'none', the vertical scrollbar - will never be displayed. If 'static', the scrollbar will always - be displayed. If 'dynamic', the scrollbar will be displayed - only if necessary. The default is 'dynamic'.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
borderframe -
-A frame widget which snuggly fits around the clipper, to give the - appearance of a border. It is created with a border so that the - clipper, which is created without a border, looks like it has a - border. By default, this component is a Tkinter.Frame.

- - -
- -
clipper -
-The frame which is used to provide a clipped view of the frame - component. If the borderframe option is true, this is created - with a borderwidth of 0 to overcome a known problem with using - place to position widgets: if a widget (in this case the - frame component) is placed inside a frame (in this case the - clipper component) and it extends across one of the edges of the - frame, then the widget obscures the border of the frame. - Therefore, if the clipper has no border, then this overlapping - does not occur. By default, this component is a Tkinter.Frame.

- - -
- -
frame -
-The frame within the clipper to contain the widgets to be scrolled. By default, this component is a Tkinter.Frame.

- - -
- -
horizscrollbar -
-The horizontal scrollbar. By default, this component is a Tkinter.Scrollbar. Its component group is Scrollbar.

- - -
- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Frame.

- - -
- -
label -
-If the labelpos option is not None, this component is - created as a text label for the megawidget. See the - labelpos option for details. Note that to set, for example, - the text option of the label, you need to use the label_text - component option. By default, this component is a Tkinter.Label.

- - -
- -
vertscrollbar -
-The vertical scrollbar. By default, this component is a Tkinter.Scrollbar. Its component group is Scrollbar.

- - -
-
- -

Methods

-Only methods specific to this megawidget are described below. -For a description of its inherited methods, see the -manual for its base class -Pmw.MegaWidget. -

- -
interior()
-Return the frame within which the programmer may create widgets to - be scrolled. This is the same as component('frame').

- - -
- -
reposition()
-Update the position of the frame component in the clipper and - update the scrollbars.

-

Usually, this method does not need to be called explicitly, since - the position of the frame component and the scrollbars are - automatically updated whenever the size of the frame or - clipper components change or the user clicks in the scrollbars. - However, if horizflex or vertflex is 'expand', the - megawidget cannot detect when the requested size of the frame - increases to greater than the size of the clipper. Therefore, - this method should be called when a new widget is added to the - frame (or a widget is increased in size) after the initial - megawidget construction.

- - - -
- -
xview(mode = None, value = None, units = None)
-Query or change the horizontal position of the scrollable interior - frame. If mode is None, return a tuple of two numbers, each - between 0.0 and 1.0. The first is the position of the left edge - of the visible region of the contents of the scrolled frame, - expressed as a fraction of the total width of the contents. The - second is the position of the right edge of the visible region.

-

If mode == 'moveto', adjust the view of the interior so that - the fraction value of the total width of the contents is - off-screen to the left. The value must be between 0.0 and - 1.0.

- -

If mode == 'scroll', adjust the view of the interior left or - right by a fixed amount. If what is 'units', move the view in - units of horizfraction. If what is pages, move the view in - units of the width of the scrolled frame. If value is positive, - move to the right, otherwise move to the left.

- - - -
- -
yview(mode = None, value = None, units = None)
-Query or change the vertical position of the scrollable interior - frame. If mode is None, return a tuple of two numbers, each - between 0.0 and 1.0. The first is the position of the top edge - of the visible region of the contents of the scrolled frame, - expressed as a fraction of the total height of the contents. The - second is the position of the bottom edge of the visible region.

-

If mode == 'moveto', adjust the view of the interior so that - the fraction value of the total height of the contents is - off-screen to the top. The value must be between 0.0 and - 1.0.

- -

If mode == 'scroll', adjust the view of the interior up or - down by a fixed amount. If what is 'units', move the view in - units of vertfraction. If what is pages, move the view in - units of the height of the scrolled frame. If value is - positive, move to down, otherwise move up.

- - - -
-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-        # Create the ScrolledFrame.
-        self.sf = Pmw.ScrolledFrame(parent,
-                labelpos = 'n', label_text = 'ScrolledFrame',
-                usehullsize = 1,
-                hull_width = 400,
-                hull_height = 220,
-        )
-
-        # Create a group widget to contain the flex options.
-        w = Pmw.Group(parent, tag_text='Flex')
-        w.pack(side = 'bottom', padx = 5, pady = 3)
-
-        hflex = Pmw.OptionMenu(w.interior(),
-                labelpos = 'w',
-                label_text = 'Horizontal:',
-                items = ['fixed', 'expand', 'shrink', 'elastic'],
-                command = self.sethflex,
-                menubutton_width = 8,
-        )
-        hflex.pack(side = 'left', padx = 5, pady = 3)
-        hflex.invoke('fixed')
-
-        vflex = Pmw.OptionMenu(w.interior(),
-                labelpos = 'w',
-                label_text = 'Vertical:',
-                items = ['fixed', 'expand', 'shrink', 'elastic'],
-                command = self.setvflex,
-                menubutton_width = 8,
-        )
-        vflex.pack(side = 'left', padx = 5, pady = 3)
-        vflex.invoke('fixed')
-
-        # Create a group widget to contain the scrollmode options.
-        w = Pmw.Group(parent, tag_text='Scroll mode')
-        w.pack(side = 'bottom', padx = 5, pady = 0)
-
-        hmode = Pmw.OptionMenu(w.interior(),
-                labelpos = 'w',
-                label_text = 'Horizontal:',
-                items = ['none', 'static', 'dynamic'],
-                command = self.sethscrollmode,
-                menubutton_width = 8,
-        )
-        hmode.pack(side = 'left', padx = 5, pady = 3)
-        hmode.invoke('dynamic')
-
-        vmode = Pmw.OptionMenu(w.interior(),
-                labelpos = 'w',
-                label_text = 'Vertical:',
-                items = ['none', 'static', 'dynamic'],
-                command = self.setvscrollmode,
-                menubutton_width = 8,
-        )
-        vmode.pack(side = 'left', padx = 5, pady = 3)
-        vmode.invoke('dynamic')
-
-        self.radio = Pmw.RadioSelect(parent, selectmode = 'multiple',
-            command = self.radioSelected)
-        self.radio.add('center', text = 'Keep centered vertically')
-        self.radio.pack(side = 'bottom')
-
-        buttonBox = Pmw.ButtonBox(parent)
-        buttonBox.pack(side = 'bottom')
-        buttonBox.add('add', text = 'Add a button', command = self.addButton)
-        buttonBox.add('yview', text = 'Show yview', command = self.showYView)
-        buttonBox.add('scroll', text = 'Page down', command = self.pageDown)
-
-        # Pack this last so that the buttons do not get shrunk when
-        # the window is resized.
-        self.sf.pack(padx = 5, pady = 3, fill = 'both', expand = 1)
-
-        self.frame = self.sf.interior()
-
-        self.row = 0
-        self.col = 0
-
-        for count in range(15):
-            self.addButton()
-
-    def sethscrollmode(self, tag):
-        self.sf.configure(hscrollmode = tag)
-
-    def setvscrollmode(self, tag):
-        self.sf.configure(vscrollmode = tag)
-
-    def sethflex(self, tag):
-        self.sf.configure(horizflex = tag)
-
-    def setvflex(self, tag):
-        self.sf.configure(vertflex = tag)
-
-    def addButton(self):
-        button = Tkinter.Button(self.frame,
-            text = '(%d,%d)' % (self.col, self.row))
-        button.grid(row = self.row, column = self.col, sticky = 'nsew')
-
-        self.frame.grid_rowconfigure(self.row, weight = 1)
-        self.frame.grid_columnconfigure(self.col, weight = 1)
-        if self.sf.cget('horizflex') == 'expand' or \
-                self.sf.cget('vertflex') == 'expand':
-            self.sf.reposition()
-
-        if 'center' in self.radio.getcurselection():
-            self.sf.update_idletasks()
-            self.centerPage()
-
-        if self.col == self.row:
-            self.col = 0
-            self.row = self.row + 1
-        else:
-            self.col = self.col + 1
-
-    def showYView(self):
-        print self.sf.yview()
-
-    def pageDown(self):
-        self.sf.yview('scroll', 1, 'page')
-
-    def radioSelected(self, name, state):
-        if state:
-            self.centerPage()
-
-    def centerPage(self):
-        # Example of how to use the yview() method of Pmw.ScrolledFrame.
-        top, bottom = self.sf.yview()
-        size = bottom - top
-        middle = 0.5 - size / 2
-        self.sf.yview('moveto', middle)
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 18 February 2001 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/ScrolledListBox.gif b/Pmw/Pmw_1_2/doc/ScrolledListBox.gif deleted file mode 100644 index 9a595618..00000000 Binary files a/Pmw/Pmw_1_2/doc/ScrolledListBox.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/ScrolledListBox.html b/Pmw/Pmw_1_2/doc/ScrolledListBox.html deleted file mode 100644 index 0c12d76e..00000000 --- a/Pmw/Pmw_1_2/doc/ScrolledListBox.html +++ /dev/null @@ -1,379 +0,0 @@ - - - - - - Pmw.ScrolledListBox reference manual - - - - -

Pmw.ScrolledListBox

- -
-
-

Name

-

Pmw.ScrolledListBox() - - listbox with optional scrollbars -

- - -
-

Inherits

-Pmw.MegaWidget
-
-

Description

-

- A scrolled listbox consists of a standard listbox widget with optional - scrollbars which can be used to scroll the listbox. The - scrollbars can be dynamic, which means that a scrollbar will - only be displayed if it is necessary. That is, if the listbox - does not contain enough entries, the vertical scrollbar will be - automatically hidden and if the entries are not wide enough, the - horizontal scrollbar will be automatically hidden.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
dblclickcommand -
-This specifies a function to call when mouse button 1 is double - clicked over an entry in the listbox component. The default is None.

- - -
- -
hscrollmode -
-The horizontal scroll mode. If 'none', the horizontal scrollbar - will never be displayed. If 'static', the scrollbar will always - be displayed. If 'dynamic', the scrollbar will be displayed - only if necessary. The default is 'dynamic'.

- - -
- -
items -
-Initialisation option. A tuple containing the initial items to be displayed by the - listbox component. The default is ().

- - -
- -
labelmargin -
-Initialisation option. If the labelpos option is not None, this specifies the - distance between the label component and the rest of the - megawidget. The default is 0.

- - -
- -
labelpos -
-Initialisation option. Specifies where to place the label component. If not - None, it should be a concatenation of one or two of the - letters 'n', 's', 'e' and 'w'. The first letter - specifies on which side of the megawidget to place the label. - If a second letter is specified, it indicates where on that - side to place the label. For example, if labelpos is 'w', - the label is placed in the center of the left hand side; if - it is 'wn', the label is placed at the top of the left - hand side; if it is 'ws', the label is placed at the - bottom of the left hand side.

-

If None, a label component is not created. The default is None.

- - - -
- -
scrollmargin -
-Initialisation option. The distance between the scrollbars and the listbox widget. The default is 2.

- - -
- -
selectioncommand -
-This specifies a function to call when mouse button 1 is single - clicked over an entry in the listbox component or if the <Space> - or <Return> key is hit while the listbox has focus. The default is None.

- - -
- -
usehullsize -
-Initialisation option. If true, the size of the megawidget is determined solely by the - width and height options of the hull component.

-

Otherwise, the size of the megawidget is determined by the width - and height of the listbox component, along with the size and/or - existence of the other components, such as the label, the - scrollbars and the scrollmargin option. All these affect the - overall size of the megawidget. The default is 0.

- - - -
- -
vscrollmode -
-The vertical scroll mode. If 'none', the vertical scrollbar - will never be displayed. If 'static', the scrollbar will always - be displayed. If 'dynamic', the scrollbar will be displayed - only if necessary. The default is 'dynamic'.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
horizscrollbar -
-The horizontal scrollbar. By default, this component is a Tkinter.Scrollbar. Its component group is Scrollbar.

- - -
- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Frame.

- - -
- -
label -
-If the labelpos option is not None, this component is - created as a text label for the megawidget. See the - labelpos option for details. Note that to set, for example, - the text option of the label, you need to use the label_text - component option. By default, this component is a Tkinter.Label.

- - -
- -
listbox -
-The listbox widget which is scrolled by the scrollbars. By default, this component is a Tkinter.Listbox.

- - -
- -
vertscrollbar -
-The vertical scrollbar. By default, this component is a Tkinter.Scrollbar. Its component group is Scrollbar.

- - -
-
- -

Methods

-Only methods specific to this megawidget are described below. -For a description of its inherited methods, see the -manual for its base class -Pmw.MegaWidget. -In addition, methods from the -Tkinter.Listbox class -are forwarded by this megawidget to the -listbox component. -

- -
bbox(index)
-This method is explicitly forwarded to the listbox component's - bbox() method. Without this explicit forwarding, the bbox() - method (aliased to grid_bbox()) of the hull would be invoked, - which is probably not what the programmer intended.

- - -
- -
clear()
-Delete all items from the scrolled listbox. Equivalent to - setlist(()).

- - -
- -
get(first = None, last = None)
-This is the same as the get() method of the listbox component, - except that if first is None all list - elements are returned.

- - -
- -
getcurselection()
-Same as getvalue() method.

- - -
- -
getvalue()
-Return a list of the currently selected items of the listbox.

- - -
- -
setlist(items)
-Replace all the items of the listbox component with those - specified by the items sequence.

- - -
- -
setvalue(textOrList)
-Set the current selection for the scrolled list to textOrList.

-

If textOrList is a string, select only the list item specified.

- -

Otherwise, select only the list items specified by textOrList, - which must be a sequence of strings.

- - - -
- -
size()
-This method is explicitly forwarded to the listbox component's - size() method. Without this explicit forwarding, the size() - method (aliased to grid_size()) of the hull would be invoked, - which is probably not what the programmer intended.

- - -
-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-        # Create the ScrolledListBox.
-        self.box = Pmw.ScrolledListBox(parent,
-                items=('Sydney', 'Melbourne', 'Brisbane'),
-                labelpos='nw',
-                label_text='Cities',
-                listbox_height = 6,
-                selectioncommand=self.selectionCommand,
-                dblclickcommand=self.defCmd,
-                usehullsize = 1,
-                hull_width = 200,
-                hull_height = 200,
-        )
-
-        # Create a group widget to contain the scrollmode options.
-        w = Pmw.Group(parent, tag_text='Scroll mode')
-        w.pack(side = 'bottom', padx = 5, pady = 5)
-
-        hmode = Pmw.OptionMenu(w.interior(),
-                labelpos = 'w',
-                label_text = 'Horizontal:',
-                items = ['none', 'static', 'dynamic'],
-                command = self.sethscrollmode,
-                menubutton_width = 8,
-        )
-        hmode.pack(side = 'top', padx = 5, pady = 5)
-        hmode.invoke('dynamic')
-
-        vmode = Pmw.OptionMenu(w.interior(),
-                labelpos = 'w',
-                label_text = 'Vertical:',
-                items = ['none', 'static', 'dynamic'],
-                command = self.setvscrollmode,
-                menubutton_width = 8,
-        )
-        vmode.pack(side = 'top', padx = 5, pady = 5)
-        vmode.invoke('dynamic')
-
-        buttonBox = Pmw.ButtonBox(parent)
-        buttonBox.pack(side = 'bottom')
-        buttonBox.add('yview', text = 'Show\nyview', command = self.showYView)
-        buttonBox.add('scroll', text = 'Page\ndown', command = self.pageDown)
-        buttonBox.add('center', text = 'Center', command = self.centerPage)
-
-        # Pack this last so that the buttons do not get shrunk when
-        # the window is resized.
-        self.box.pack(fill = 'both', expand = 1, padx = 5, pady = 5)
-
-        # Do this after packing the scrolled list box, so that the
-        # window does not resize as soon as it appears (because
-        # alignlabels has to do an update_idletasks).
-        Pmw.alignlabels((hmode, vmode))
-
-        # Add some more entries to the listbox.
-        items = ('Andamooka', 'Coober Pedy', 'Innamincka', 'Oodnadatta')
-        self.box.setlist(items)
-        self.box.insert(2, 'Wagga Wagga', 'Perth', 'London')
-        self.box.insert('end', 'Darwin', 'Auckland', 'New York')
-        index = list(self.box.get(0, 'end')).index('London')
-        self.box.delete(index)
-        self.box.delete(7, 8)
-        self.box.insert('end', 'Bulli', 'Alice Springs', 'Woy Woy')
-        self.box.insert('end', 'Wallumburrawang', 'Willandra Billabong')
-
-    def sethscrollmode(self, tag):
-        self.box.configure(hscrollmode = tag)
-
-    def setvscrollmode(self, tag):
-        self.box.configure(vscrollmode = tag)
-
-    def selectionCommand(self):
-        sels = self.box.getcurselection()
-        if len(sels) == 0:
-            print 'No selection'
-        else:
-            print 'Selection:', sels[0]
-
-    def defCmd(self):
-        sels = self.box.getcurselection()
-        if len(sels) == 0:
-            print 'No selection for double click'
-        else:
-            print 'Double click:', sels[0]
-
-    def showYView(self):
-        print self.box.yview()
-
-    def pageDown(self):
-        self.box.yview('scroll', 1, 'page')
-
-    def centerPage(self):
-        top, bottom = self.box.yview()
-        size = bottom - top
-        middle = 0.5 - size / 2
-        self.box.yview('moveto', middle)
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 30 August 1998 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/ScrolledText.gif b/Pmw/Pmw_1_2/doc/ScrolledText.gif deleted file mode 100644 index b766c95b..00000000 Binary files a/Pmw/Pmw_1_2/doc/ScrolledText.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/ScrolledText.html b/Pmw/Pmw_1_2/doc/ScrolledText.html deleted file mode 100644 index 1acbccc6..00000000 --- a/Pmw/Pmw_1_2/doc/ScrolledText.html +++ /dev/null @@ -1,409 +0,0 @@ - - - - - - Pmw.ScrolledText reference manual - - - - -

Pmw.ScrolledText

- -
-
-

Name

-

Pmw.ScrolledText() - - text widget with optional scrollbars -

- - -
-

Inherits

-Pmw.MegaWidget
-
-

Description

-

- A scrolled text consists of a standard text widget with optional - scrollbars which can be used to scroll the text. The - scrollbars can be dynamic, which means that a scrollbar will - only be displayed if it is necessary. That is, if the text widget - does not contain enough text (either horizontally or vertically), - the scrollbar will be automatically hidden. If it is displayed, - the horizontal scrollbar is under the text widget. Similarly, if - it is displayed, the vertical scrollbar is to the right of the - text widget.

- -

Row and column headers may also be displayed, which scroll in sync - with the text widget and may be useful when displaying tabular - data. To assist in ensuring that columns line up when using a - column header, a fixed width font should be used.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
borderframe -
-Initialisation option. If true, the borderframe component will be created. The default is 0.

- - -
- -
columnheader -
-Initialisation option. If true, the columnheader component will be created. The default is 0.

- - -
- -
hscrollmode -
-The horizontal scroll mode. If 'none', the horizontal scrollbar - will never be displayed. If 'static', the scrollbar will always - be displayed. If 'dynamic', the scrollbar will be displayed - only if necessary. The default is 'dynamic'.

- - -
- -
labelmargin -
-Initialisation option. If the labelpos option is not None, this specifies the - distance between the label component and the rest of the - megawidget. The default is 0.

- - -
- -
labelpos -
-Initialisation option. Specifies where to place the label component. If not - None, it should be a concatenation of one or two of the - letters 'n', 's', 'e' and 'w'. The first letter - specifies on which side of the megawidget to place the label. - If a second letter is specified, it indicates where on that - side to place the label. For example, if labelpos is 'w', - the label is placed in the center of the left hand side; if - it is 'wn', the label is placed at the top of the left - hand side; if it is 'ws', the label is placed at the - bottom of the left hand side.

-

If None, a label component is not created. The default is None.

- - - -
- -
rowcolumnheader -
-Initialisation option. If true, the rowcolumnheader component will be created. The default is 0.

- - -
- -
rowheader -
-Initialisation option. If true, the rowheader component will be created. The default is 0.

- - -
- -
scrollmargin -
-Initialisation option. The distance between the scrollbars and the text widget. The default is 2.

- - -
- -
usehullsize -
-Initialisation option. If true, the size of the megawidget is determined solely by the - width and height options of the hull component.

-

Otherwise, the size of the megawidget is determined by the width - and height of the text component, along with the size and/or - existence of the other components, such as the label, the - scrollbars and the scrollmargin option. All these affect the - overall size of the megawidget. The default is 0.

- - - -
- -
vscrollmode -
-The vertical scroll mode. If 'none', the vertical scrollbar - will never be displayed. If 'static', the scrollbar will always - be displayed. If 'dynamic', the scrollbar will be displayed - only if necessary. The default is 'dynamic'.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
borderframe -
-A frame widget which snuggly fits around the text widget, to give - the appearance of a text border. It is created with a border so - that the text widget, which is created without a border, looks - like it has a border. By default, this component is a Tkinter.Frame.

- - -
- -
columnheader -
-A text widget with a default height of 1 displayed above the main - text widget and which scrolls horizontally in sync with the - horizontal scrolling of the main text widget. By default, this component is a Tkinter.Text. Its component group is Header.

- - -
- -
horizscrollbar -
-The horizontal scrollbar. By default, this component is a Tkinter.Scrollbar. Its component group is Scrollbar.

- - -
- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Frame.

- - -
- -
label -
-If the labelpos option is not None, this component is - created as a text label for the megawidget. See the - labelpos option for details. Note that to set, for example, - the text option of the label, you need to use the label_text - component option. By default, this component is a Tkinter.Label.

- - -
- -
rowcolumnheader -
-A text widget displayed to the top left of the main text widget, - above the row header and to the left of the column header if they - exist. The widget is not scrolled automatically. By default, this component is a Tkinter.Text. Its component group is Header.

- - -
- -
rowheader -
-A text widget displayed to the left of the main text widget and - which scrolls vertically in sync with the vertical scrolling of - the main text widget. By default, this component is a Tkinter.Text. Its component group is Header.

- - -
- -
text -
-The text widget which is scrolled by the scrollbars. If the - borderframe option is true, this is created with a borderwidth - of 0 to overcome a known problem with text widgets: if a widget - inside a text widget extends across one of the edges of the text - widget, then the widget obscures the border of the text widget. - Therefore, if the text widget has no border, then this overlapping - does not occur. By default, this component is a Tkinter.Text.

- - -
- -
vertscrollbar -
-The vertical scrollbar. By default, this component is a Tkinter.Scrollbar. Its component group is Scrollbar.

- - -
-
- -

Methods

-Only methods specific to this megawidget are described below. -For a description of its inherited methods, see the -manual for its base class -Pmw.MegaWidget. -In addition, methods from the -Tkinter.Text class -are forwarded by this megawidget to the -text component. -

- -
appendtext(text)
-Add text to the end of the text component. Scroll to the - bottom of the text, but only if it was already visible before the - new text was added.

- - -
- -
bbox(index)
-This method is explicitly forwarded to the text component's - bbox() method. Without this explicit forwarding, the bbox() - method (aliased to grid_bbox()) of the hull would be invoked, - which is probably not what the programmer intended.

- - -
- -
clear()
-Delete all text from the text component.

- - -
- -
exportfile(fileName)
-Write the contents of the text component to the file fileName.

- - -
- -
get(first = None, last = None)
-This is the same as the get() method of the text component, - except that if first is None the entire - contents of the text widget are returned.

- - -
- -
getvalue()
-Return the entire contents of the text widget.

- - -
- -
importfile(fileName, where = 'end')
-Read the contents of the file fileName and insert into the - text component at the position given by where.

- - -
- -
settext(text)
-Same as setvalue() method.

- - -
- -
setvalue(text)
-Replace the entire contents of the text component with text.

- - -
-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-
-        # Create the ScrolledText with headers.
-        fixedFont = Pmw.logicalfont('Fixed')
-        self.st = Pmw.ScrolledText(parent,
-                # borderframe = 1,
-                labelpos = 'n',
-                label_text='ScrolledText with headers',
-                columnheader = 1,
-                rowheader = 1,
-                rowcolumnheader = 1,
-                usehullsize = 1,
-                hull_width = 400,
-                hull_height = 300,
-                text_wrap='none',
-                text_font = fixedFont,
-                Header_font = fixedFont,
-                Header_foreground = 'blue',
-                rowheader_width = 3,
-                rowcolumnheader_width = 3,
-                text_padx = 4,
-                text_pady = 4,
-                Header_padx = 4,
-                rowheader_pady = 4,
-        )
-
-        self.st.pack(padx = 5, pady = 5, fill = 'both', expand = 1)
-
-        funcs = 'atan cos cosh exp log log10 sin sinh sqrt tan tanh'
-        funcs = string.split(funcs)
-
-        # Create the header for the row headers
-        self.st.component('rowcolumnheader').insert('end', 'x')
-
-        # Create the column headers
-        headerLine = ''
-        for column in range(len(funcs)):
-            headerLine = headerLine + ('%-7s   ' % (funcs[column],))
-        headerLine = headerLine[:-3]
-        self.st.component('columnheader').insert('0.0', headerLine)
-
-        self.st.tag_configure('yellow', background = 'yellow')
-
-        # Create the data rows and the row headers
-        numRows = 50
-        tagList = []
-        for row in range(1, numRows):
-            dataLine = ''
-            x = row / 5.0
-            for column in range(len(funcs)):
-                value = eval('math.' + funcs[column] + '(' + str(x) + ')')
-                data = str(value)[:7]
-                if value < 0:
-                    tag1 = '%d.%d' % (row, len(dataLine))
-                    tag2 = '%d.%d' % (row, len(dataLine) + len(data))
-                    tagList.append(tag1)
-                    tagList.append(tag2)
-                data = '%-7s' % (data,)
-                dataLine = dataLine + data + '   '
-            dataLine = dataLine[:-3]
-            header = '%.1f' % (x,)
-            if row < numRows - 1:
-                dataLine = dataLine + '\n'
-                header = header + '\n'
-            self.st.insert('end', dataLine)
-            self.st.component('rowheader').insert('end', header)
-        apply(self.st.tag_add, ('yellow',) + tuple(tagList))
-
-        # Prevent users' modifying text and headers
-        self.st.configure(
-            text_state = 'disabled',
-            Header_state = 'disabled',
-        )
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 30 August 1998 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/ScrolledText_test.py b/Pmw/Pmw_1_2/doc/ScrolledText_test.py deleted file mode 100644 index 53a5ab48..00000000 --- a/Pmw/Pmw_1_2/doc/ScrolledText_test.py +++ /dev/null @@ -1,116 +0,0 @@ -# Based on iwidgets2.2.0/tests/scrolledtext.test code. - -import Test -import Pmw - -Test.initialise() - -c = Pmw.ScrolledText - -def _testYView(doBottom): - w = Test.currentWidget() - top, bottom = w.yview() - if type(top) != type(0.0) or type(bottom) != type(0.0): - return 'bad type ' + str(top) + ' ' + str(bottom) - if doBottom: - if bottom != 1.0: - return 'bottom is ' + str(bottom) - else: - if top != 0.0: - return 'top is ' + str(top) - -kw_1 = {'labelpos': 'n', 'label_text': 'ScrolledText'} -tests_1 = ( - (c.pack, (), {'padx' : 10, 'pady' : 10, 'fill' : 'both', 'expand' : 1}), - (Test.num_options, (), 10), - (c.importfile, 'ScrolledText_test.py'), - ('hull_background', 'aliceblue'), - ('text_borderwidth', 3), - ('Scrollbar_borderwidth', 3), - ('hull_cursor', 'gumby'), - ('text_exportselection', 0), - ('text_exportselection', 1), - ('text_foreground', 'Black'), - ('text_height', 10), - ('text_width', 20), - ('text_insertbackground', 'Black'), - ('text_insertborderwidth', 1), - ('text_insertofftime', 200), - ('text_insertontime', 500), - ('text_insertwidth', 3), - ('label_text', 'Label'), - ('text_relief', 'raised'), - ('text_relief', 'sunken'), - ('Scrollbar_repeatdelay', 200), - ('Scrollbar_repeatinterval', 105), - ('vscrollmode', 'none'), - ('vscrollmode', 'static'), - ('vscrollmode', 'dynamic'), - ('hscrollmode', 'none'), - ('hscrollmode', 'static'), - ('hscrollmode', 'dynamic'), - ('Scrollbar_width', 20), - ('text_selectborderwidth', 2), - ('text_state', 'disabled'), - ('text_state', 'normal'), - ('text_background', 'GhostWhite'), - ('text_wrap', 'char'), - ('text_wrap', 'none'), - ('vscrollmode', 'bogus', 'ValueError: bad vscrollmode ' + - 'option "bogus": should be static, dynamic, or none'), - ('hscrollmode', 'bogus', 'ValueError: bad hscrollmode ' + - 'option "bogus": should be static, dynamic, or none'), - (c.cget, 'vscrollmode', 'bogus'), - (c.cget, 'hscrollmode', 'bogus'), - ('vscrollmode', 'dynamic'), - ('hscrollmode', 'dynamic'), - (c.insert, ('end', 'Hello there\n')), - (_testYView, 0), - (c.yview, ('moveto', 0.02)), - (c.yview, ('moveto', 0.04)), - (c.yview, ('moveto', 0.06)), - (c.yview, ('moveto', 0.08)), - (c.yview, ('moveto', 0.10)), - (c.yview, ('moveto', 0.12)), - (c.yview, ('moveto', 0.14)), - (c.yview, ('moveto', 0.16)), - (c.yview, ('moveto', 0.18)), - (c.yview, ('moveto', 0.20)), - (c.yview, ('moveto', 0.22)), - (c.yview, ('moveto', 0.24)), - (c.yview, ('moveto', 0.26)), - (c.yview, ('moveto', 0.28)), - (c.yview, ('moveto', 0.98)), - (_testYView, 1), - (c.yview, ('scroll', -1, 'page')), - (c.yview, ('scroll', -50, 'page')), - (_testYView, 0), - (c.yview, ('scroll', 1, 'page')), - (c.yview, ('scroll', 50, 'page')), - (_testYView, 1), - (c.clear, ()), - (c.get, (), '\n'), -) - -kw_2 = { - 'hscrollmode' : 'dynamic', - 'label_text' : 'Label', - 'labelpos' : 'n', - 'scrollmargin': 20, -} -tests_2 = ( - (c.pack, (), {'padx' : 10, 'pady' : 10, 'fill' : 'both', 'expand' : 1}), - (c.importfile, 'ScrolledText_test.py'), - ('text_relief', 'raised'), - ('text_relief', 'sunken'), -) - -alltests = ( - (tests_1, kw_1), - (tests_2, kw_2), -) - -testData = ((Pmw.ScrolledText, alltests),) - -if __name__ == '__main__': - Test.runTests(testData) diff --git a/Pmw/Pmw_1_2/doc/SelectionDialog.gif b/Pmw/Pmw_1_2/doc/SelectionDialog.gif deleted file mode 100644 index 1d6f3dd9..00000000 Binary files a/Pmw/Pmw_1_2/doc/SelectionDialog.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/SelectionDialog.html b/Pmw/Pmw_1_2/doc/SelectionDialog.html deleted file mode 100644 index c4708232..00000000 --- a/Pmw/Pmw_1_2/doc/SelectionDialog.html +++ /dev/null @@ -1,281 +0,0 @@ - - - - - - Pmw.SelectionDialog reference manual - - - - -

Pmw.SelectionDialog

- -
-
-

Name

-

Pmw.SelectionDialog() - - selection dialog displaying a scrolled list -

- - -
-

Inherits

-Pmw.Dialog
-
-

Description

-

- The selection dialog is a dialog window which displays a scrolled - list which can be used to prompt the user for a value.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
activatecommand -
-If this is callable, it will be called whenever the megawidget is - activated by a call to activate(). The default is None.

- - -
- -
borderx -
-Initialisation option. The padding to the left and right of the scrolled list. The default is 10.

- - -
- -
bordery -
-Initialisation option. The padding above and below the scrolled list. The default is 10.

- - -
- -
buttonboxpos -
-Initialisation option. Specifies on which side of the dialog window to place the button - box. Must be one of 'n', 's', 'e' or 'w'. The default is 's'.

- - -
- -
buttons -
-This must be a tuple or a list and specifies the names on the - buttons in the button box. The default is ('OK',).

- - -
- -
command -
-Specifies a function to call whenever a button in the button box - is invoked or the window is deleted by the window manager. The - function is called with a single argument, which is the name of - the button which was invoked, or None if the window was deleted - by the window manager.

-

If the value of command is not callable, the default behaviour - is to deactivate the window if it is active, or withdraw the - window if it is not active. If it is deactivated, deactivate() - is called with the button name or None as described above. The default is None.

- - - -
- -
deactivatecommand -
-If this is callable, it will be called whenever the megawidget is - deactivated by a call to deactivate(). The default is None.

- - -
- -
defaultbutton -
-Specifies the default button in the button box. If the <Return> - key is hit when the dialog has focus, the default button will be - invoked. If defaultbutton is None, there will be no default - button and hitting the <Return> key will have no effect. The default is None.

- - -
- -
master -
-This is used by the activate() method to control whether the - window is made transient during modal dialogs. See the - activate() method. The default is 'parent'.

- - -
- -
separatorwidth -
-Initialisation option. If this is greater than 0, a separator line with the specified - width will be created between the button box and the child site, - as a component named separator. Since the default border of the - button box and child site is raised, this option does not - usually need to be set for there to be a visual separation between - the button box and child site. The default is 0.

- - -
- -
title -
-This is the title that the window manager displays in the title - bar of the window. The default is None.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
buttonbox -
-This is the button box containing the buttons for the dialog. By - default it is created with the options - (hull_borderwidth = 1, hull_relief = 'raised'). By default, this component is a Pmw.ButtonBox.

- - -
- -
dialogchildsite -
-This is the child site for the dialog, which may be used to - specialise the megawidget by creating other widgets within it. By - default it is created with the options - (borderwidth = 1, relief = 'raised'). By default, this component is a Tkinter.Frame.

- - -
- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Toplevel.

- - -
- -
scrolledlist -
-The scrolled list for the user to enter a value. By default, this component is a Pmw.ScrolledListBox.

- - -
- -
separator -
-If the separatorwidth initialisation option is non-zero, the - separator component is the line dividing the area between the - button box and the child site. By default, this component is a Tkinter.Frame.

- - -
-
-

Component aliases

-Sub-components of components of this megawidget -may be accessed via the following aliases.

-
label -
-Alias for scrolledlist_label. -
-
listbox -
-Alias for scrolledlist_listbox. -
-
- -

Methods

-Only methods specific to this megawidget are described below. -For a description of its inherited methods, see the -manual for its base class -Pmw.Dialog. -In addition, methods from the -Pmw.ScrolledListBox class -are forwarded by this megawidget to the -scrolledlist component. -

- -
bbox(index)
-This method is explicitly forwarded to the listbox component's - bbox() method. Without this explicit forwarding, the bbox() - method (aliased to grid_bbox()) of the hull would be invoked, - which is probably not what the programmer intended.

- - -
- -
size()
-This method is explicitly forwarded to the listbox component's - size() method. Without this explicit forwarding, the size() - method (aliased to grid_size()) of the hull would be invoked, - which is probably not what the programmer intended.

- - -
-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-        # Create the dialog.
-        self.dialog = Pmw.SelectionDialog(parent,
-            title = 'My SelectionDialog',
-            buttons = ('OK', 'Cancel'),
-            defaultbutton = 'OK',
-            scrolledlist_labelpos = 'n',
-            label_text = 'What do you think of Pmw?',
-            scrolledlist_items = ('Cool man', 'Cool', 'Good', 'Bad', 'Gross'),
-            command = self.execute)
-        self.dialog.withdraw()
-
-        # Create button to launch the dialog.
-        w = Tkinter.Button(parent, text = 'Show selection dialog',
-                command = self.dialog.activate)
-        w.pack(padx = 8, pady = 8)
-
-    def execute(self, result):
-        sels = self.dialog.getcurselection()
-        if len(sels) == 0:
-            print 'You clicked on', result, '(no selection)'
-        else:
-            print 'You clicked on', result, sels[0]
-        self.dialog.deactivate(result)
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 18 May 2002 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/TextDialog.gif b/Pmw/Pmw_1_2/doc/TextDialog.gif deleted file mode 100644 index 4438828d..00000000 Binary files a/Pmw/Pmw_1_2/doc/TextDialog.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/TextDialog.html b/Pmw/Pmw_1_2/doc/TextDialog.html deleted file mode 100644 index 3f4995f4..00000000 --- a/Pmw/Pmw_1_2/doc/TextDialog.html +++ /dev/null @@ -1,301 +0,0 @@ - - - - - - Pmw.TextDialog reference manual - - - - -

Pmw.TextDialog

- -
-
-

Name

-

Pmw.TextDialog() - - a dialog displaying a scrolled text -

- - -
-

Inherits

-Pmw.Dialog
-
-

Description

-

- A text dialog is a dialog window which displays a text message to - the user along with one or more buttons to press.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
activatecommand -
-If this is callable, it will be called whenever the megawidget is - activated by a call to activate(). The default is None.

- - -
- -
borderx -
-Initialisation option. The padding to the left and right of the scrolled text. The default is 10.

- - -
- -
bordery -
-Initialisation option. The padding above and below the scrolled text. The default is 10.

- - -
- -
buttonboxpos -
-Initialisation option. Specifies on which side of the dialog window to place the button - box. Must be one of 'n', 's', 'e' or 'w'. The default is 's'.

- - -
- -
buttons -
-This must be a tuple or a list and specifies the names on the - buttons in the button box. The default is ('OK',).

- - -
- -
command -
-Specifies a function to call whenever a button in the button box - is invoked or the window is deleted by the window manager. The - function is called with a single argument, which is the name of - the button which was invoked, or None if the window was deleted - by the window manager.

-

If the value of command is not callable, the default behaviour - is to deactivate the window if it is active, or withdraw the - window if it is not active. If it is deactivated, deactivate() - is called with the button name or None as described above. The default is None.

- - - -
- -
deactivatecommand -
-If this is callable, it will be called whenever the megawidget is - deactivated by a call to deactivate(). The default is None.

- - -
- -
defaultbutton -
-Specifies the default button in the button box. If the <Return> - key is hit when the dialog has focus, the default button will be - invoked. If defaultbutton is None, there will be no default - button and hitting the <Return> key will have no effect. The default is None.

- - -
- -
master -
-This is used by the activate() method to control whether the - window is made transient during modal dialogs. See the - activate() method. The default is 'parent'.

- - -
- -
separatorwidth -
-Initialisation option. If this is greater than 0, a separator line with the specified - width will be created between the button box and the child site, - as a component named separator. Since the default border of the - button box and child site is raised, this option does not - usually need to be set for there to be a visual separation between - the button box and child site. The default is 0.

- - -
- -
title -
-This is the title that the window manager displays in the title - bar of the window. The default is None.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
buttonbox -
-This is the button box containing the buttons for the dialog. By - default it is created with the options - (hull_borderwidth = 1, hull_relief = 'raised'). By default, this component is a Pmw.ButtonBox.

- - -
- -
dialogchildsite -
-This is the child site for the dialog, which may be used to - specialise the megawidget by creating other widgets within it. By - default it is created with the options - (borderwidth = 1, relief = 'raised'). By default, this component is a Tkinter.Frame.

- - -
- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Toplevel.

- - -
- -
scrolledtext -
-The scrolled text to contain the text for the dialog. By default, this component is a Pmw.ScrolledText.

- - -
- -
separator -
-If the separatorwidth initialisation option is non-zero, the - separator component is the line dividing the area between the - button box and the child site. By default, this component is a Tkinter.Frame.

- - -
-
-

Component aliases

-Sub-components of components of this megawidget -may be accessed via the following aliases.

-
label -
-Alias for scrolledtext_label. -
-
text -
-Alias for scrolledtext_text. -
-
- -

Methods

-Only methods specific to this megawidget are described below. -For a description of its inherited methods, see the -manual for its base class -Pmw.Dialog. -In addition, methods from the -Pmw.ScrolledText class -are forwarded by this megawidget to the -scrolledtext component. -

- -
bbox(index)
-This method is explicitly forwarded to the text component's - bbox() method. Without this explicit forwarding, the bbox() - method (aliased to grid_bbox()) of the hull would be invoked, - which is probably not what the programmer intended.

- - -
-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-        # Create the dialog.
-        dialog = Pmw.TextDialog(parent, scrolledtext_labelpos = 'n',
-                title = 'My TextDialog',
-                defaultbutton = 0,
-                label_text = 'Lawyer jokes')
-        dialog.withdraw()
-        dialog.insert('end', jokes)
-        dialog.configure(text_state = 'disabled')
-
-        # Create button to launch the dialog.
-        w = Tkinter.Button(parent, text = 'Show text dialog',
-                command = dialog.activate)
-        w.pack(padx = 8, pady = 8)
-
-jokes = """
-Q: What do you call 5000 dead lawyers at the bottom of the ocean?
-A: A good start!
-
-Q: How can you tell when a lawyer is lying?
-A: His lips are moving.
-
-Q: Why won't sharks attack lawyers?
-A: Professional courtesy.
-
-Q: What do have when a lawyer is buried up to his neck in sand?
-A: Not enough sand.
-
-Q: How do you get a lawyer out of a tree?
-A: Cut the rope.
-
-Q: What is the definition of a shame (as in "that's a shame")?
-A: When a bus load of lawyers goes off a cliff.
-
-Q: What is the definition of a "crying shame"?
-A: There was an empty seat.
-
-Q: What do you get when you cross the Godfather with a lawyer?
-A: An offer you can't understand.
-
-Q. What do lawyers use as contraceptives?
-A. Their personalities.
-
-Q. What's brown and black and looks good on a lawyer?
-A. A doberman.
-
-Q. Why are lawyers buried 12 feet underground?
-A. Deep down their good.
-
-Q. What's the difference between a catfish and a lawyer?
-A. One's a slimy scum-sucking scavenger, the other is just a fish.
-
-"""
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 18 May 2002 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/TimeCounter.gif b/Pmw/Pmw_1_2/doc/TimeCounter.gif deleted file mode 100644 index 26cbdba5..00000000 Binary files a/Pmw/Pmw_1_2/doc/TimeCounter.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/TimeCounter.html b/Pmw/Pmw_1_2/doc/TimeCounter.html deleted file mode 100644 index 6fbdea33..00000000 --- a/Pmw/Pmw_1_2/doc/TimeCounter.html +++ /dev/null @@ -1,363 +0,0 @@ - - - - - - Pmw.TimeCounter reference manual - - - - -

Pmw.TimeCounter

- -
-
-

Name

-

Pmw.TimeCounter() - - counter for display and input of time -

- - -
-

Inherits

-Pmw.MegaWidget
-
-

Description

-

- A time counter is similar to a regular Pmw.Counter except that the - user may increment and decrement the hours, minutes and seconds - individually.

- -

- - -
-

Options

-Options for this megawidget and its base -classes are described below.

- -
autorepeat -
-If true, the counter will continue to count up or down while an - arrow button is held pressed down. The default is 1.

- - -
- -
buttonaspect -
-Initialisation option. Specifies the width of the arrow buttons as a proportion of their - height. Values less than 1.0 will produce thin arrow buttons. - Values greater than 1.0 will produce fat arrow buttons. The default is 1.0.

- - -
- -
command -
-This specifies a function to call whenever the <Return> key is - pressed in one of the entry fields or invoke() is called. The default is None.

- - -
- -
initwait -
-Specifies the initial delay (in milliseconds) before a depressed - arrow button automatically starts to repeat counting. The default is 300.

- - -
- -
labelmargin -
-Initialisation option. If the labelpos option is not None, this specifies the - distance between the label component and the rest of the - megawidget. The default is 0.

- - -
- -
labelpos -
-Initialisation option. Specifies where to place the label component. If not - None, it should be a concatenation of one or two of the - letters 'n', 's', 'e' and 'w'. The first letter - specifies on which side of the megawidget to place the label. - If a second letter is specified, it indicates where on that - side to place the label. For example, if labelpos is 'w', - the label is placed in the center of the left hand side; if - it is 'wn', the label is placed at the top of the left - hand side; if it is 'ws', the label is placed at the - bottom of the left hand side.

-

If None, a label component is not created. The default is None.

- - - -
- -
max -
-Specifies the maximum acceptable time in the form "HH:MM:SS", or - None if no maximum checking should be performed. The default is None.

- - -
- -
min -
-Specifies the minimum acceptable time in the form "HH:MM:SS", or - None if no minimum checking should be performed. The default is None.

- - -
- -
padx -
-Initialisation option. Specifies how much wider to make each column than the default - width (where a column consists of two arrows and an entry field). - The entry fields expand to fill the extra space, but the arrow - buttons are centered in the available space. The default is 0.

- - -
- -
pady -
-Initialisation option. Specifies how much higher to make each row of arrow buttons than - the default hight. The arrow buttons are centered in the - available space. The default is 0.

- - -
- -
repeatrate -
-Specifies the delay (in milliseconds) between automatic counts - while an arrow button is held pressed down. The default is 50.

- - -
- -
value -
-Initialisation option. Specifies the initial contents of the time counter, in the form - "HH:MM:SS". If this is None, the current time is used as the - initial contents. The default is None.

- - -
-
-

Components

-Components created by this megawidget and its base -classes are described below.

- -
downhourarrow -
-The arrow button used for decrementing the hour field. By default, this component is a Tkinter.Canvas. Its component group is Arrow.

- - -
- -
downminutearrow -
-The arrow button used for decrementing the minute field. By default, this component is a Tkinter.Canvas. Its component group is Arrow.

- - -
- -
downsecondarrow -
-The arrow button used for decrementing the second field. By default, this component is a Tkinter.Canvas. Its component group is Arrow.

- - -
- -
frame -
-If the label component has been created (that is, the labelpos - option is not None), the frame component is created to act as - the container of the entry fields and arrow buttons. If there is - no label component, then no frame component is created and the - hull component acts as the container. In either case the border - around the container of the entry fields and arrow buttons will be - raised (but not around the label). By default, this component is a Tkinter.Frame.

- - -
- -
hourentryfield -
-The entry field where the hours are entered and displayed. By default, this component is a Pmw.EntryField.

- - -
- -
hull -
-This acts as the body for the entire megawidget. Other components - are created as children of the hull to further specialise this - class. By default, this component is a Tkinter.Frame.

- - -
- -
label -
-If the labelpos option is not None, this component is - created as a text label for the megawidget. See the - labelpos option for details. Note that to set, for example, - the text option of the label, you need to use the label_text - component option. By default, this component is a Tkinter.Label.

- - -
- -
minuteentryfield -
-The entry field where the minutes are entered and displayed. By default, this component is a Pmw.EntryField.

- - -
- -
secondentryfield -
-The entry field where the seconds are entered and displayed. By default, this component is a Pmw.EntryField.

- - -
- -
uphourarrow -
-The arrow button used for incrementing the hour field. By default, this component is a Tkinter.Canvas. Its component group is Arrow.

- - -
- -
upminutearrow -
-The arrow button used for incrementing the minute field. By default, this component is a Tkinter.Canvas. Its component group is Arrow.

- - -
- -
upsecondarrow -
-The arrow button used for incrementing the second field. By default, this component is a Tkinter.Canvas. Its component group is Arrow.

- - -
-
-

Component aliases

-Sub-components of components of this megawidget -may be accessed via the following aliases.

-
hourentry -
-Alias for hourentryfield_entry. -
-
minuteentry -
-Alias for minuteentryfield_entry. -
-
secondentry -
-Alias for secondentryfield_entry. -
-
- -

Methods

-Only methods specific to this megawidget are described below. -For a description of its inherited methods, see the -manual for its base class -Pmw.MegaWidget. -

- -
decrement(seconds = 1)
-Decrement the time by seconds seconds.

- - -
- -
getint()
-Return the currently displayed time as a number of seconds.

- - -
- -
getstring()
-Same as getvalue() method.

- - -
- -
getvalue()
-Return the currently displayed time as a string in the form - "HH:MM:SS".

- - -
- -
increment(seconds = 1)
-Increment the time by seconds seconds.

- - -
- -
invoke()
-Invoke the command specified by the command option as if the - <Return> key had been pressed.

- - -
- -
setvalue(text)
-Set the contents of the time counter, where text must be in the - form "HH:MM:SS".

- - -
-
-

Example

-The image at the top of this manual is a snapshot -of the window (or part of the window) produced -by the following code.

-
-class Demo:
-    def __init__(self, parent):
-        self._time = Pmw.TimeCounter(parent,
-                labelpos = 'w',
-                label_text = 'HH:MM:SS',
-                min = '00:00:00',
-                max = '23:59:59')
-        self._time.pack(padx=10, pady=5)
-
-        button = Tkinter.Button(parent, text = 'Show', command = self.show)
-        button.pack()
-
-    def show(self):
-        stringVal = self._time.getstring()
-        intVal =  self._time.getint()
-        print stringVal + '  (' + str(intVal) + ')'
-
-
-
-
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home -
Manual page last reviewed: 25 May 2002 -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/blue_line.gif b/Pmw/Pmw_1_2/doc/blue_line.gif deleted file mode 100644 index 2063df02..00000000 Binary files a/Pmw/Pmw_1_2/doc/blue_line.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/blueball.gif b/Pmw/Pmw_1_2/doc/blueball.gif deleted file mode 100644 index 013183af..00000000 Binary files a/Pmw/Pmw_1_2/doc/blueball.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/bugs.html b/Pmw/Pmw_1_2/doc/bugs.html deleted file mode 100644 index f46e8e9e..00000000 --- a/Pmw/Pmw_1_2/doc/bugs.html +++ /dev/null @@ -1,378 +0,0 @@ - - - - - - List of known bugs - - - - -

List of known bugs

- -

-This is a list of some of the known bugs in Pmw. If you fix any of -these, please let the maintainer (gregm@iname.com) know.

-
  • Under the Enlightenment window manager, if show() is called when - a window is already displayed (and is not obscured by other - windows), then the application will hang for two seconds. This - is either a bug in Tcl/Tk or in Enlightenment. See the comment - in the Tk function WaitForConfigureNotify() in the Tk source - file tk8.3.2/unix/tkUnixWm.c:

    -
     /*
    -  * One more tricky detail about this procedure.  In some cases the
    -  * window manager will decide to ignore a configure request (e.g.
    -  * because it thinks the window is already in the right place).
    -  * To avoid hanging in this situation, only wait for a few seconds,
    -  * then give up.
    -  */
    - - -
  • -
  • On NT, Pmw.MenuBar does not display message bar help for menu - items. It seems that Tk menu widgets do not support <Motion> - events on MS. This probably is an issue that should be taken up - with the Tcl/Tk people. (Reported by Stefan Schone. Pmw.0.7)

    - -
  • -
  • Run the CounterDialog.py demo, select the show dialog button and - press ok. Now exit the dialog (either with the exit button or - the close box). The following error appears:

    -
     Menu ID 256 is already in use!Fatal Python Error: Tcl/Tk panic
    - -

    This may be a problem with Mac version of Tk. (Reported by - Anthony Wilson.)

    - - -
  • -
  • Pmw.Balloons bind to widgets and canvas items. This means that - bindings made by other users are deleted when the balloon makes - its bindings. (For example, the "Delete" canvas item in the - Balloon demo overrides that <ButtonPress> binding and so that - balloon is not withdrawn when the mouse button is pressed over - the item.)

    -

    The obvious solution is for Pmw.Balloon to add its bindings with - a +. But this would make the unbind and tagunbind methods - inconsistent - they would remove all bindings, not just the ones - added by the balloon. A better way would be for the balloon to - add a bindtag to each widget`s bindtag list - then it would not - upset any other bindings and it could be deleted cleanly. - (Reported by Joe Saltiel)

    - - -
- -
 import Tkinter
- import Pmw
- 
- def foo(event):
-     print '<Enter> event on text'
- 
- root = Pmw.initialise()
- balloon = Pmw.Balloon()
- 
- canvas = Tkinter.Canvas()
- canvas.pack()
- 
- text1 = canvas.create_text(50, 50, text = 'hello
-there')
- 
- # As is, the balloon does not appear over the text, but foo
- # is called.  Swap the following two lines and the balloon
- # appears but foo will not be called.
- canvas.tag_bind(text1, "<Enter>", foo)
- balloon.tagbind(canvas, text1, 'text 1 help')
- 
- root.mainloop()
-
  • In Pmw.Balloon, the balloon should not be withdrawn when the - pointer leaves a widget or item and it immediatly enters another - widget or item with balloon help. Instead, the balloon should - be moved and its contents changed immediately.

    - -
  • -
  • When a Pmw.Balloon is bound to a canvas item, moving the item - becomes very slow. (Reported by Joe Saltiel)

    -
     > Second, after I fixed my ordering problem I noticed, there
    - > is a pretty big delay in updating widgets that have balloon
    - > messages bound to them.  (For example dragging a box across
    - > a screen, the box has a delayed reaction.) I believe this is
    - > due to some of the timing functions used in PmwBalloon, I am
    - > not sure if there is a way around it.  I set all timers to
    - > zero, and still had the problem.
    - - -
  • -
  • When running Pmw demos under ptui the busy cursor does not - appear.

    - -
  • -
  • If a combobox has a horizontal scrollbar and it displays its - listbox above the entry, then it is misplaced.

    - -
  • -
  • Bug in Pmw.PanedWidget: repeat by creating new panes in Demo - - existing panes jump to the right 1 or 2 pixels.

    - -
  • -
  • Bug in Pmw.PanedWidget: repeat by setting hull_borderwidth to - 20 in demo - initial drag jumps to right by about 20 pixels. - Also right hand side border is missing. (Fix may be similar to - method used in Pmw.ScrolledFrame to give canvas border.)

    - -
  • -
  • Fix ButtonRelease events so they do not trigger without a - corresponding ButtonPress event.

    -

    From Joe Saltiel: I was playing around with a scrolledlistbox - and tkFileDialog. When I have the dialog open above the list - box and I doubleclick on it, I invoke the selectioncmd of the - listbox as well as the tkFileDialog box, should this be - happening?

    - -

    Attached is small sample program you can try. To get the bug to - show you must do two things. First, when you open the file - dialog box, make sure the item you are going to select if - over(above) the scrolledlistbox. Second, you have to double - click on that item. If you single click and hit "Open" you do - not get the bug. Nor do you get it unless the file you click on - is directly over the clickable region of the scrolledlist box.

    -
     import Tkinter
    - import Pmw
    - import tkFileDialog
    - import string 
    - 
    - def askOpen():
    -     file = tkFileDialog.askopenfile(filetypes=[("all files", "*")])  
    -     print file
    - 
    - def printMe():
    -     print "Me"
    - 
    - root = Tkinter.Tk()
    - Pmw.initialise(root)
    - 
    - frame1 = Tkinter.Frame(root)
    - lst = string.split("abc def ghi jkl mno pqr stu vwx yz")
    - lstbox = Pmw.ScrolledListBox(frame1, items=lst, selectioncommand=printMe)
    - lstbox.grid(row=0, column=0, columnspan=2)
    - Tkinter.Button(frame1, text='open', command=askOpen).grid(row=1, column=0)
    - Tkinter.Button(frame1, text='exit', command=root.destroy).grid(row=1, column=1)
    - frame1.pack()
    - 
    - root.mainloop()
    - - -

    Response: I have found where the problem is but I am not sure - how to fix it. It appears that the tkFileDialog box closes on a - ButtonPress event. The corresponding ButtonRelease event is - then sent to whichever widget is under the cursor at the time of - the Release. I have reproduced the problem with a Tcl-only - script:

    -
     listbox .l
    - .l insert 0 1 2 3 4
    - bind .l <ButtonRelease-1> {puts AAAGGHHH!}
    -
    - button .b -text open -command tk_getOpenFile
    - pack .l .b
    - - -

    If you do a quick Press-Release-Press over the file dialog, it - is withdrawn. If you then keep the mouse button down and move - the mouse around, you will see that the button and the listbox - still respond to it. If you do the final button Release over - the listbox, its <ButtonRelease-1> binding is invoked.

    - -

    I think the correct solution is to modify Pmw to be very careful - when to accept ButtonRelease events. It will need to also bind - to ButtonPress events and make sure that it gets a Press before - it accepts the Release. I'll try to do the change as soon as - possible, but the code involved is fairly complex so I it may - take a little time.

    - - -
  • -
  • Investigate bug in Tk8.0: When a dialog pops up over the - pointer then the keyboard focus is not set and so <Return> does - not invoke default button.

    - -
  • -
  • Under both X and NT, the arrows in the timecounter, counter and - combobox do not match the scrollbar arrows.

    - -
  • -
  • Pmw.Group does not work correctly when the tag is a compound - widget. The tag is placed such that the top of the tag is cut - off. (Reported by Peter Stoehr.)

    -
     import Tkinter
    - import Pmw
    - 
    - root = Tkinter.Tk()
    - Pmw.initialise(root, fontScheme = 'pmw1')
    - exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy)
    - exitButton.pack(side = 'bottom')
    - 
    - def makeGroup(tagClassName):
    -     tagClass = eval(tagClassName)
    -     group = Pmw.Group(
    -         tag_pyclass = tagClass,
    -         hull_background = 'red',
    -         groupchildsite_background = 'blue',
    -     )
    -     group.pack(fill = 'both', expand = 1, padx = 6, pady = 6)
    -     child = Tkinter.Label(group.interior(),
    -         text = 'Group with tag ' + tagClassName,
    -         background = 'aliceblue',
    -     )
    -     child.pack(padx = 10, pady = 5, expand = 1, fill = 'both')
    -
    -     return group
    - 
    - grp1 = makeGroup('Pmw.EntryField')
    - grp2 = makeGroup('Pmw.ComboBox')
    - grp3 = makeGroup('Tkinter.Entry')
    - 
    - root.mainloop()
    - -

    Also, Pmw.Group does not resize correctly if the simple widget - changes size. For example:

    -
     grp3.configure(tag_font = ('Helveltica', '-160'))
    - - - -
  • -
  • Bug(s) in PmwScrolledCanvas. There is a bug in 0.8.1 - PmwScrolledCanvas._setRegion. If there are no objects in the - canvas, then error occurs on len(region) because region is None. - Below is an attempt to fix it. Click on Show, then on Delete. - The window then continuously resizes. If the ScrolledCanvas is - created with canvasmargin = 0, the problem goes away. (Reported - by Anders Henja.)

    -
     import Tkinter
    - import Pmw
    - 
    - def _setRegion(self):
    -     # Attempt to fix PmwScrolledCanvas._setRegion.
    -     self.setregionTimer = None
    - 
    -     region = self._canvas.bbox('all')
    -     canvasmargin = self['canvasmargin']
    -     if region is None:
    -         region = (0, 0, 0, 0)
    -     region = (region[0] - canvasmargin, region[1] - canvasmargin,
    -         region[2] + canvasmargin, region[3] + canvasmargin)
    -     self._canvas.configure(scrollregion = region)
    - 
    - def show():
    -     canvas.component('canvas').delete('all')
    -     canvas.create_oval(0, 0, 800, 600, fill = 'red')
    -     canvas.configure(canvas_width = 600, canvas_height = 450)
    -     canvas.resizescrollregion()
    - 
    - def delete():
    -     canvas.component('canvas').delete('all')
    -     canvas.configure(canvas_width = 0, canvas_height = 0)
    -     canvas.resizescrollregion()
    - 
    - root=Tkinter.Tk()
    - Pmw.initialise(root)
    - 
    - buttonbox=Pmw.ButtonBox()
    - buttonbox.pack(fill='x',side='bottom',padx=5,pady=5)
    - buttonbox.add('Show',command=show)
    - buttonbox.add('Delete',command=delete)
    - buttonbox.alignbuttons()
    - 
    - canvas=Pmw.ScrolledCanvas(canvasmargin=2)
    - canvas.__class__._setRegion = _setRegion
    - canvas.pack(fill='both',side='right',expand=1)
    - 
    - root.mainloop()
    - - -
  • -
  • Bug in Pmw.Dialog: if defaultbutton is configured before - buttons during self.initialiseoptions() (that is if - self._constructorKeywords.keys() returns a different order), - then setdefault() fails.

    - -
  • -
  • Bugs in Tk which affect Pmw.MainMenuBar:

    -
    • Extra bindings assigned to a Tkinter.Menu widget using - bindtags have no effect. Hence the method used in - Pmw.MenuBar for status help (bind_class followed by - bindtags) does not work and therefore binding to the menu - widget is used instead.

      - -
    • -
    • The 'active' tag for the index() method of Tkinter.Menu - always returns None. Hence, in the menu widget motion - binding, event.y and the '@' format is used instead, for - all menus except the toplevel main menu.

      - -
    • -
    • For the toplevel main menu, event.x must be used for the - index() method, but it returns the wrong index. It - appears that the Tk widget is assuming vertical layout - to calculate distances, rather than horizontal.

      - -
    • -
    • For toplevel main menus, several Tk commands, such as - winfo_height(), do not work. This prevents the use of - balloon help for Pmw.MainMenuBar.

      - -
    - -
  • -
  • Bug in Pmw.ComboBox: Tab to combobox arrow, use up/down arrow - keys to change selection, hit return, nothing happens, <Shift - Tab> to entry window, hit return, combobox changes

    -
    • actually, it would be better if you could not tab to - the arrow, only the entry field, like the Pmw.Counter.

      - -
    • -
    • the problem is if the entry field is not editable, what to - do then?

      - -
    - -
  • -
  • Bug in TimeCounter: Arrow keys don't work when focus is on entry.

    - -
  • -
  • Bug in Pmw.NoteBook: The size of the tab does not change when - the text value changes

    - -
  • -
  • Bug in Pmw.NoteBook: The name of the tab components has a "-" sign - in it, which means that component options can not be used in the - configure command. Eg:

    -
     n = Pmw.NoteBook()
    - p = n.add('page1')
    - n.configure(page1_background = 'red')   # works
    - n.configure(page1-tab_background = 'red')   # fail, must do this:
    - n.component('page1-tab').configure(background = 'red')   # works
    - - -
-

- - - - -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home - -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/changes.html b/Pmw/Pmw_1_2/doc/changes.html deleted file mode 100644 index f3dd6402..00000000 --- a/Pmw/Pmw_1_2/doc/changes.html +++ /dev/null @@ -1,1741 +0,0 @@ - - - - - - Changes to Pmw - - - - -

Changes to Pmw

- -

- 6 January 1997

- -
  • Release of version 0.1

    - -
-

14 February 1997

- -
  • Fixed bug in Counter demo for the Macintosh - the maximum size of an - integer is smaller than the value returned by time.time().

    - -
  • -
  • Fixed bug in Grid demo for Tk 4.2 - grid_bbox returns garbage if it is - called without update_idletasks. Also, grid_bbox can only have two - arguments in Tk 4.1.

    - -
  • -
  • Modified ScrolledText demo so that the text widget contains enough text - to require a vertical scrollbar.

    - -
  • -
  • Changes to PmwBase:

    -
    • Prefixed the name of several private variables with a double underscore.

      - -
    • -
    • Added symbolic constants for the indexes into an optionInfo list.

      - -
    • -
    • Changed names of several methods and variables to be more descriptive.

      - -
    • -
    • Removed options() method.

      - -
    • -
    • Simplified configuration option data structures. Modified option - handling code so that default options are set correctly. If an - option is created before initialise() is called then initialise() - checks if the option is set by the keyword arguments to - initialise(). If not, then it is given the value found in the - Tk option database, if a value exists, or the default value. If an - option is created after initialise() is called, then it is given the - value found in the Tk option database, if a value exists, or the - default value.

      - -
    - -
  • -
  • Replaced usage of self._hull in megawidgets by interior() method.

    - -
  • -
  • Added autoclear option to ComboBox.

    - -
  • -
  • Fixed bug in ComboBox - fast clicking on the arrow button could result - in an attempt to grab a window that was not yet visible.

    - -
  • -
  • Added "sys.exc_traceback = None" to the except clauses of all try - statements so that references to objects in the stack trace would not - be left.

    - -
  • -
  • Added takefocus option to PushButton.

    - -
  • -
  • Modified the getcurselection() method of ScrolledListBox so that it - returns a string if the selection mode is 'single' or 'browse', rather - than a tuple with one element. This also affects methods forwarded and - derived from ScrolledListBox.

    - -
  • -
  • Modified ScrolledListBox so that it avoids unnecessary updates by - using idle timer.

    - -
  • -
  • Modified ScrolledText to use grid instead of pack.

    - -
  • -
  • Added shutdown() function to Tk module to clean up all references to - the Tcl interpreter and then delete it.

    - -
  • -
  • Fixed bug in Tk module for the Macintosh - update() was being called in - initialise() before the Tcl interpreter was created.

    - -
-

14 February 1997

- -
  • Version 0.1.1 completed and released internally.

    - -
-

6 March 1997

- -
  • Pmw now uses the standard Tkinter module. The Tk module has been - dropped. This means that the Tk module functions such as after, - bell, bind, update, etc, are no longer available and the equivalent - Tkinter methods should be used.

    - -
  • -
  • To restore some of the features of the Tk module, Pmw.initialise() - now adds run-time hooks into Tkinter to get notification of when Tk - widgets are created and destroyed. It also modifies the CallWrapper - class so that errors during callbacks and bindings can be displayed - in a window. If Pmw.initialise() is not called, Tkinter is not - modified and these features are not available.

    - -
  • -
  • If a Tk widget which is acting as the hull of a megawidget is - destroyed, then the megawidget is destroyed as well. This can - only happen if Pmw.initialise() is called.

    - -
  • -
  • Pmw.initialise() now takes the Tkinter root as its argument.

    - -
  • -
  • The parent of megawidgets now defaults to the Tk root. Previously, - the parent of non-toplevel megawidgets had to be given.

    - -
  • -
  • Added PmwBase.tracetk() function to get trace of calls to the Tcl - interpreter for debugging.

    - -
  • -
  • Added functions to PmwBase to display a busy cursor over the - application such as when a modal dialog is displayed or it is - blocked doing a long calculation. Uses busy command of the blt - extension, if present.

    - -
  • -
  • Created a nifty new demo which demonstrates most of the megawidgets - in a convenient way.

    - -
  • -
  • Added a TextDialog.

    - -
  • -
  • Added functionality to handle the grabbing of nested modal dialogs - correctly.

    - -
  • -
  • Added an activatecommand option to Dialog which allows, for example, - the PromptDialog widget to set the keyboard focus when it is - activated.

    - -
  • -
  • Added tests for Counter and logicalfont.

    - -
  • -
  • The ScrolledListBox selectioncommand is no longer given the widget - as its first argument.

    - -
  • -
  • Several method, function and component names were changed, to be - consistent with the coding conventions.

    - -
  • -
  • Some of the effects of moving from the Tk module to Tkinter are:

    -
    • The Tk module used to exit if there were no non-root toplevel - windows shown. This is no longer the case and so the application - must handle this explicitly, particularly if the root window is - withdrawn and the last non-root toplevel is deleted by the window - manager.

      - -
    • -
    • The Tk module bind functions and methods used to take a noEvent - argument to indicate that the Tk event should not be passed to the - callback. Tkinter does not support this.

      - -
    • -
    • The Tk module initialise() function should be replaced by - "root = Tkinter.Tk()" and root should be used instead of "Tk.Root()"

      - -
    • -
    • The Tk module quit() function should be replace by "root.destroy()".

      - -
    • -
    • Toplevels are not hidden when created. To be consistent, - MegaToplevels are not hidden either.

      - -
    • -
    • The hide and show methods are not available for Tkinter Toplevels, - only MegaToplevels

      - -
    • -
    • There is no grid_configure method.

      - -
    • -
    • Tkinter.Canvas.coords() returns a python list, not a tuple.

      - -
    • -
    • The Tkinter cget and configure widget methods always return - strings for the option values. The Tk module used to convert the - string to the appropriate python type (such as string, integer, - float, Variable, Image, callback function).

      - -
    • -
    • Tkinter Menu and Toplevel classes incorrectly have a pack method.

      - -
    • -
    • Menu class has no geometry method.

      - -
    • -
    • Canvas focus returns '' rather than None.

      - -
    • -
    • Text mark_gravity returns '' rather than None.

      - -
    - -
-

13 March 1997

- -
  • Release of version 0.2

    - -
-

17 March 1997

- -
  • Set default WM_DELETE_WINDOW protocol of Tkinter.Toplevel to - destroy() and removed duplicated protocol request from all demos.

    - -
  • -
  • Modified text of ShowBusy demo to indicate that busy cursor will - only be seen if the BLT extension is present.

    - -
  • -
  • Replaced call to update() in PmwLabeledWidget.py with update_idletasks().

    - -
  • -
  • Changed name of PromptDialog component from 'entry' to 'entryfield'.

    - -
-

28 April 1997

- -
  • Version 0.3 released internally

    - -
-

19 August 1997

- -
  • Many changes made (see the version 0.4 porting guide for - more details).

    - -
  • -
  • The option propagation mechanism that iwidgets uses is too - cumbersome, too hard to understand and, in python, too slow. - Developed a new mechanism which is more explicit in naming - options. This resulted in most options which were simply - propagated to components being removed. Removed keep(), rename() - and ignore() methods and "usual" options.

    - -
  • -
  • For speed, Pmw no longer queries the Tk option database for - default values for megawidget options. Hence, resource names and - classes do not need to be supplied when creating options and - None is returned for the resource name and class when using - configure() to query the options. Option "types" no longer - used.

    - -
  • -
  • Changed method and component names to be more consistent.

    - -
  • -
  • Replaced most uses of pack() with grid().

    - -
  • -
  • Megawidgets no longer inherit from LabeledWidget. Instead they - call createlabel() to optionally create the label component.

    - -
  • -
  • Removed child site from EntryField and rewrote ComboBox - accordingly.

    - -
  • -
  • Wrote lots more documentation, including automatically generated - reference manuals.

    - -
  • -
  • Removed PushButton and rewrote ButtonBox to directly create - Tkinter.Buttons rather than PushButtons.

    - -
  • -
  • Added initialisation options - options which can be set at - creation time but not later using configure().

    - -
  • -
  • Added aliases for components.

    - -
  • -
  • Modified the base classes so that during option configuration, - components are configured before configuration called functions - are called.

    - -
  • -
  • Added several more megawidgets.

    - -
  • -
  • Added interface to BLT graph and vector commands.

    - -
  • -
  • Created PmwLazy module for lazy importing of Pmw - avoids loading - megawidgets which are not used.

    - -
  • -
  • Added several more functions for handling color and fonts.

    - -
  • -
  • Replaced Counter and EntryField time with timeN and time24

    - -
  • -
  • Pmw.initialise() will now create Tkinter.Tk if not given root.

    - -
-

1 September 1997

- -
  • Release of version 0.4

    - -
-

5 September 1997

- -
  • Modified the base classes so that the Tk option database resource - class of megawidgets can be overridden in the call to the - constructor using the hull_class option.

    - -
  • -
  • The separators in Pmw.PanedWidget are now active - they can be - grabbed, like the handles, and moved around. The cursor now - changes to the correct left/right or up/down cursor when over a - separator or handle. (Clemens Hintze)

    - -
  • -
  • Fixed bug in MessageInfo demo Dismiss button. If it is invoked, - an error occurs saying "not enough arguments". (Mark Colclough)

    - -
-

9 September 1997

- -
  • Added the useTkOptionDb argument to Pmw.initialise which - specifies that the initial values of megawidget options are to be - set by querying the Tk option database.

    - -
  • -
  • When used to query options, the configure() method now returns the - resource class and name of the options.

    - -
-

19 September 1997

- -
  • Changed functions datestringtoint() and timestringtoint() to - datestringtojdn() and timestringtoseconds(). Changed return value - of datestringtojdn() to be Julian Day Numbers rather than seconds - since the epoch.

    - -
  • -
  • Fixed a bug in the date Counter due to use of time.timezone, by - replacing, when calculating date increments, calls to the time - module with calls to datestringtojdn().

    - -
  • -
  • Added century pivot year (setyearpivot function) to Counter date - datatypes to handle two-digit years.

    - -
  • -
  • Added date_dmy4, date_mdy4 and date_y4md datatypes to Counter.

    - -
  • -
  • Modified demos All.py and ScrolledText.py so that demos can be called - from directories other than the demos directory. (Case Roole and - Guido van Rossum)

    - -
  • -
  • Changed the default for the Pmw.Balloon label_justify option to - left to improve appearance of multi-line balloons. Pmw.Balloon - now replaces newlines with spaces in the statusHelp string so that - the strings look better when displayed in a Pmw.MessageBar. - (Andreas Kostyrka)

    - -
  • -
  • Pmw.Blt now calls package require BLT when checking for the - existence of Blt, so that it can be loaded if it is not statically - linked. (Clemens Hintze, Matthias Klose)

    - -
  • -
  • Copied earthris.gif and flagup.bmp files from Tcl distribution to - test directory, just in case they have not been installed. - (Jonathan Kelly)

    - -
  • -
  • Lots of improvements to the documentation and documenting recent - changes.

    - -
-

16 October 1997

- -
  • Modified Pmw.Balloon and Pmw.ComboBox to work around a bug in the - Windows95 version of Tk which caused the popup windows to appear - in the wrong place. (Fredrik Lundh and Jerome Gay)

    - -
  • -
  • Added Pmw.maxfontwidth() function. (Rob Pearson)

    - -
-

24 October 1997

- -
  • Changed PmwBase._reporterror to handle the class exceptions of - python 1.5. (Case Roole)

    - -
-

29 October 1997

- -
  • Fixed a bug in forwardmethods() function which occurred if the - toClass class had a method called type.

    - -
-

7 November 1997

- -
  • Changed tests/Test._getErrorValue to handle the class exceptions of - python 1.5. (Michael McLay)

    - -
  • -
  • Changed bug fix in forwardmethods() function to use the - exec execString in d construct. (Guido van Rossum)

    - -
  • -
  • Can now use Pmw.MegaArchetype as a base class just to get option - handling; it will not create the hull component unless requested. - Moved __str__() and interior() methods from Pmw.MegaToplevel and - Pmw.MegaWidget to Pmw.MegaArchetype class.

    - -
-

10 November 1997

- -
  • Added textclass option to Pmw.ScrolledText and listboxclass - option for Pmw.ScrolledListBox to allow embedding of custom - widgets.

    - -
  • -
  • Added Mitch Chapman's FontText module to the demos directory - and used it to display the demo source code in color.

    - -
  • -
  • Added two notebook megawwidgets, Pmw.NoteBookR and Pmw.NoteBookS. - (Case Roole and Joe Saltiel)

    - -
  • -
  • Added Pmw.ScrolledCanvas megawidget. (Joe Saltiel)

    - -
  • -
  • Added Pmw.TreeBrowse megawidget. (Michael McLay)

    - -
  • -
  • Added Pmw.Group megawidget and modified to use grid() instead - of pack(). (Case Roole)

    - -
  • -
  • Release of version 0.5

    - -
-

12 November 1997

- -
  • Added pyclass option to components and removed textclass - option from Pmw.ScrolledText and listboxclass option from - Pmw.ScrolledListBox. (Suggested by Shen Wang)

    - -
  • -
  • Added label component to Pmw.ButtonBox megawidget.

    - -
  • -
  • Fixed mis-spelling of PmwTreeBrowse in Pmw.py.

    - -
  • -
  • Release of version 0.5.1

    - -
-

5 December 1997

- -
  • The pyclass option can now be None. If so, createcomponent - returns None.

    - -
  • -
  • Removed tagtype option from Pmw.Group. Can now use the more - general tag_pyclass instead.

    - -
  • -
  • Added tcl call to load {} Blt when testing for presence of Blt.

    - -
  • -
  • Added julian and papal options to Pmw.ymdtojulian and - Pmw.juliantoymd functions and made sure divisions give the same - result as C even when operands are negative.

    - -
  • -
  • Exported ymdtojulian and juliantoymd functions.

    - -
  • -
  • Fixed bug in activate method. Did not prepend TclError with Tkinter.

    - -
  • -
  • When the Blt busy hold command is called from showbusycursor, the - bindtags on the busy window are set so that no events cause - callbacks to occur for the toplevel or all bindings. Also, while - a busy window is up, the focus is changed to the busy window so - that no keyboard events are accepted. This fixes a bug where the - Tkinter._nametowidget function could crash with a KeyError: _Busy - if there was a binding on a toplevel window and the mouse - was pressed while the busy cursor was up.

    - -
-

9 December 1997

- -
  • Fixed bug in Pmw.datestringtojdn() when dealing with century year, - such as 2000.

    - -
-

10 December 1997

- -
  • Added where option to Pmw.ScrolledText.importfile(). (Graham - Matthews)

    - -
-

16 December 1997

- -
  • Modified Pmw.RadioSelect and Pmw.ButtonBox so that you can no - longer index their buttons using regular expressions. This - feature seemed to have little use and caused problems with buttons - labeled for example a* and b*. (Problem reported by Rob - Hooft)

    - -
  • -
  • Added updateFunction option to Pmw.busycallback(). If set, the - function will be called just after the command given to - Pmw.busycallback(). If the function is set the Tkinter update() - method, then this will clear any events that may have occurred - while the command was executing.

    - -
-

30 December 1997

- -
  • Changed ymdtojulian and juliantoymd functions to jdntoymd and - ymdtojdn, because the meaning of "julian" is ambiguous, whereas - the meaning of "Julian Day Number" is not (maybe).

    - -
  • -
  • Converted Pmw to use python 1.5 package mechanism. (Michael McLay - and Case Roole)

    - -
  • -
  • Removed Pmw.py and PmwLazy files. Added __init__.py, PmwLoader.py - and Pmw.def files. (Case Roole)

    - -
  • -
  • Applications can now specify at runtime which version of Pmw to - use and also which alpha versions, if any. (Case Roole)

    - -
  • -
  • Modified Pmw code for the version of Tkinter released with python - 1.5.

    - -
  • -
  • Release of version 0.6

    - -
-

5 January 1998

- -
  • Fixed alpha version handling so that alpha versions do not have to - supply PmwBase.py and PmwUtils.py. (Case Roole)

    - -
  • -
  • Added example alpha directory and documentation. (Case Roole)

    - -
-

7 January 1998

- -
  • Added selectmode option to Pmw.RadioSelect megawidget. (Roman - Sulzhyk)

    - -
  • -
  • Added some changes to Pmw.ScrolledCanvas to get around some bugs. - (Joe Saltiel)

    - -
  • -
  • Release of version 0.6.1

    - -
-

8 January 1998

- -
  • Added some more changes to Pmw.ScrolledCanvas. (from Joe Saltiel)

    - -
-

12 January 1998

- -
  • Added Pmw.OptionMenu megawidget. (Roman Sulzhyk)

    - -
-

20 February 1998

- -
  • Added new Pmw.MenuBar features to delete menus and menuitems, - enable and disable menu bar and to add cascade menus. (Rob Pearson)

    - -
  • -
  • Added extra arguments to Pmw.Color.spectrum for more control over - color choice.

    - -
-

23 February 1998

- -
  • Added canvasbind() method to Pmw.Balloon.

    - -
  • -
  • Fixed demos/All.py so that it will correctly determine which Pmw - version to use even if it is in a directory symlinked to the demos - directory.

    - -
  • -
  • Removed "import DemoVersion" from all demos, except All.py, so - that they will work unchanged when copied outside of the Pmw - distribution.

    - -
  • -
  • Release of version 0.6.2

    - -
-

26 February 1998

- -
  • Fixed PmwLoader so that it works on Macintoshes. (Jack Jansen)

    - -
-

2 March 1998

- -
  • Fixed PmwBase and PmwBlt so that an attempt is made to dynamically - load Blt before it is used. Previously only attempted to load Blt - when calling showbusycursor.

    - -
-

16 March 1998

- -
  • Added hulldestroyed() method.

    - -
  • -
  • Modified displayerror() function to use value given to - reporterrorstofile() if it is set.

    - -
  • -
  • Fixed bug in Pmw.EntryField which occurred when the command - option destroyed the megawidget.

    - -
  • -
  • Pmw.EntryField invoke method now passes on the value returned by - the command function.

    - -
-

3 April 1998

- -
  • Added Pmw.ScrolledFrame megawidget. (Joe Saltiel)

    - -
  • -
  • Color.rgb2hsi() now uses the built-in min() and max() functions.

    - -
-

20 April 1998

- -
  • Moved time and date functions from PmwCounter.py to new file, - PmwTimeFuncs.py.

    - -
  • -
  • Added optional separator argument to timestringtoseconds and - datestringtojdn functions. These functions are now stricter - when checking if a string is a valid date or time. For example, - it now checks for correct day in month, month in year, etc. These - changes also affect the Pmw.Counter date and time validators.

    - -
  • -
  • The datestringtojdn function now accepts all combinations of - 'd', 'm', 'y' as format string.

    - -
  • -
  • Moved functions to bottom of file and class to top of file in - PmwEntryField.py and PmwCounter.py.

    - -
  • -
  • The validation for Pmw.EntryField integer, hexadecimal and - real types now use string.atol or string.atof rather than - regular expressions.

    - -
  • -
  • The validation for the Pmw.EntryField real type accepts a - separator argument, for those who prefer a comma instead of a - full stop/period/point as the decimal dividing symbol.

    - -
  • -
  • The Pmw.EntryField time* and date_* validators have been - removed. The functionality can be replaced by using the new - time and date validators with min and max fields.

    - -
  • -
  • The Pmw.EntryField maxwidth option has been removed. The - functionality can be replaced by using the max field of the - validator.

    - -
  • -
  • Added an extravalidators option to Pmw.EntryField. This allows - new types of validation to be added, particularly in classes - derived from Pmw.EntryField. It also allows the use of different - names for the same validation, by using aliases. Added - SpecialEntry demo to show extravalidators option, based on work - by Joachim Schmitz.

    - -
  • -
  • Fixed a bug in Pmw.EntryField when combining use of value and - entry_textvariable options.

    - -
  • -
  • The Pmw.EntryField validate option now also accepts a dictionary - to handle minimum and maximum validation and to allow the passing - of other arguments to the validating functions, such as date, time - and number formats and separators.

    - -
  • -
  • Fixed bug in Pmw.EntryField where the entry would scroll to the - start of the text if an invalid character was typed.

    - -
  • -
  • Added checkentry() method to Pmw.EntryField, so that it can be - updated if the entry widget is tied to a textvariable.

    - -
-

10 May 1998

- -
  • The activate() method now takes a geometry option to allow more - flexible positioning of the modal dialog.

    - -
  • -
  • Fixed rarely occurring bug in deactivate() method if it is called - (perhaps from a timer) during the call to wait_visibility() in the - activate() method. This bug used to generate an error and the - application would not exit properly.

    - -
  • -
  • Fixed another rarely occurring bug in deactivate() method if it is - called while another application has the grab.

    - -
  • -
  • Removed "sys.exc_traceback = None" for except clauses which used - to be required by python 1.4 so that references to objects in the - stack trace would not be left.

    - -
  • -
  • Now uses sys.exc_info() function when displaying exception - traceback.

    - -
  • -
  • The state option of Pmw.Balloon and the orient option of - several others now generate an exception if they have a bad value.

    - -
  • -
  • Added a deactivatecommand option to Pmw.MegaToplevel which can be - used, for example, to cancel timers.

    - -
  • -
  • Made changes to Pmw.Counter so that the entry display continuously - changes when arrow key presses are repeated quickly.

    - -
  • -
  • Made changes to Pmw.Counter so that the insertion cursor is maintained - while counting and the entry scrolls to the end if the value is long.

    - -
  • -
  • Pmw.Counter now behaves correctly when counting past the maximum - and minimum values of the EntryField.

    - -
-

28 May 1998

- -
  • Made all Pmw.EntryField standard validators publicly available - as Pmw.numericvalidator, etc.

    - -
  • -
  • Now uses faster string.replace() instead of regsub.gsub() when - applicable.

    - -
  • -
  • If the balloonHelp argument of the Pmw.Balloon bind methods is - None, no balloon is displayed.

    - -
  • -
  • Merged the code from the PmwUtils module (forwardmethods()) into - PmwBase, since it was always used, was used nowhere else, and made - freezing a little more complicated.

    - -
  • -
  • Added a short delay between calling Tkinter bell() method (sounds nicer).

    - -
  • -
  • The functions datestringtojdn() and timestringtoseconds() now - return ValueError on invalid input.

    - -
  • -
  • Created bundlepmw.py, to help when freezing in Pmw. Placed in bin - directory.

    - -
-

29 May 1998

- -
  • Fixed rare bug in Pmw.Counter which occured if the counter was - unmapped while the mouse button was held down over an arrow button.

    - -
  • -
  • Created contrib directory and placed PmwVerticalGuage.py in it. - (Chris Wright)

    - -
  • -
  • Patched PmwNoteBookR.py. (Siggy Brentrup)

    - -
  • -
  • Added addoptions() method to Pmw.MegaArchetype class. (Dieter Maurer)

    - -
  • -
  • By default, MenuBar creates hotkeys for menus and menu items for - keyboard traversal. Added traversSpec argument to MenuBar add - methods. (Michael McLay)

    - -
-

31 May 1998

- -
  • Cleaned up bbox() methods in Pmw.ScrolledCanvas and - Pmw.ScrolledListBox.

    - -
  • -
  • The createcomponent() method now disallows the creation of - component names containing an underscore, since the query - functions would not be able to find them.

    - -
-

2 June 1998

- -
  • Release of version 0.7

    - -
-

3 June 1998

- -
  • Moved Pmw.TreeBrowse megawidget to contrib directory.

    - -
-

17 June 1998

- -
  • Added PmwFullTimeCounter.py to contrib directory (Daniel Michelson)

    - -
-

1 July 1998

- -
  • Changed mispelt file PmwVerticalGuage.py to PmwVerticalGauge.py - in contrib directory.

    - -
-

7 July 1998

- -
  • Fixed bug in Pmw.Counter real datatype. Sometimes incorrectly - counted negative decimal fractions. (Reported by David Ascher)

    - -
-

12 July 1998

- -
  • The format argument of Pmw.datestringtojdn() now defaults to - 'ymd'.

    - -
  • -
  • Removed Tkinter_test.py from tests since it does not test any Pmw - functionality (only Tkinter) and it fails under MS-Windows 95.

    - -
-

23 August 1998

- -
  • Changed several exception types to be more consistent.

    - -
  • -
  • Made the interface to Pmw.Blt.Vector more like the builtin python - list type.

    - -
  • -
  • It is no longer an error to call Pmw.setversion() or - Pmw.setalphaversions() after initialisation, as long as the - requested version matches the actual version.

    - -
  • -
  • Fixed Pmw.NoteBookR so that it behaves better when the - highlightthickness is changed.

    - -
  • -
  • The setyearpivot() function now returns a tuple containing the old - values of pivot and century.

    - -
  • -
  • Added PmwFileDialog.py to contrib directory (Rob Hooft)

    - -
  • -
  • Modified demos so that full tracebacks are displayed if an error - occurs when importing a module.

    - -
  • -
  • Removed justify() method from Pmw.ScrolledListBox, since it is - just a wrapper around the xview and yview methods of the listbox. - Also, it was not a permanent justification, as the name implied.

    - -
-

20 September 1998

- -
  • Changed implementation of Pmw.ScrolledCanvas.

    - -
  • -
  • Added borderframe option to Pmw.ScrolledText and Pmw.ScrolledCanvas.

    - -
-

18 October 1998

- -
  • Major overhaul of all scrolled widgets. Modified all to use - similar structure, given the peculiarities of each. Fixed several - subtle bugs.

    - -
  • -
  • Pmw.ScrolledFrame: now uses a frame positioned within a clipping - frame using the place geometry manager. Added borderframe, - horizflex, horizfraction, usehullsize, vertflex, vertfraction - options. Added reposition() method. Removed getFrame() method; - use interior() method instead.

    - -
  • -
  • Pmw.ScrolledListBox: added usehullsize option.

    - -
  • -
  • Pmw.ScrolledText: added borderframe and usehullsize options.

    - -
  • -
  • Pmw.ScrolledCanvas: simplified widget structure. Added - borderframe, canvasmargin, scrollmargin and usehullsize options. - Added label.

    - -
  • -
  • Modified Pmw.OptionMenu to use standard widgets rather than call - tcl procedure. Added initialitem option. Now handles - menubutton_textvariable component option correctly.

    - -
-

1 November 1998

- -
  • Documented more Pmw functions and Pmw.ComboBox.

    - -
-

15 November 1998

- -
  • Fixed some bugs, cleaned up code and wrote documentation for - Pmw.Group. Removed ringpadx and ringpady options, since this - functionality is more generally available by padding the - megawidget itself and by padding the children of the megawidget. - Modified Pmw.aligngrouptags so that it takes into account the - borderwidth and highlightthickness of the ring and so that it - works when there is no tag widget. Added tagindent option.

    - -
-

18 November 1998

- -
  • Renamed canvasbind() and canvasunbind() methods of Pmw.Balloon to - tagbind() and tagunbind() and modified so that they work with both - Tkinter.Canvas items and Tkinter.Text tagged items.

    - -
-

19 November 1998

- -
  • Added havebltbusy() method to Pmw.Blt. (Robin Becker)

    - -
-

21 November 1998

- -
  • Modified contrib/PmwFileDialog.py so that when a file is selected - with the mouse, the highlight (in the file list) persists and the - file list does not scroll to the top. (Rob Hooft)

    - -
  • -
  • Modified Pmw.Balloon so that it can be bound to a tag associated - with several Canvas or Text items. (Magnus Kessler)

    - -
-

21 November 1998

- -
  • Cleaned up appearance and colors of Pmw.NoteBookR tabs. (Georg - Mischler)

    - -
  • -
  • Added buttontype option to Pmw.RadioSelect to support - radiobuttons and checkbuttons. (Georg Mischler)

    - -
-

23 November 1998

- -
  • Updated usage of bind_class(tag) due to change in return value - in Tkinter module in python 1.5.2. (Magnus Kessler, Fredrik Lundh)

    - -
  • -
  • The default time displayed in Pmw.TimeCounter is now the current - local time, not GMT as before.

    - -
  • -
  • The times displayed in the Counter demonstration are now the - current local time, not GMT as before.

    - -
-

7 December 1998

- -
  • Modified Pmw.ComboBox to take advantage of the fix to the Tkinter - bind() method callback handling of Event.widget in python - 1.5.2. It works even if the selectioncommand destroys the - combobox. For simple comboboxes, the invoke() method now returns - the return value of the selectioncommand.

    - -
  • -
  • Modified Pmw.EntryField to take advantage of the fix to the - Tkinter bind() method callback handling of Event.widget in - python 1.5.2. It works even if a user-supplied callback - (command, invalidcommand, validator or stringtovalue) - destroys the entryfield. Cleans up correctly when destroyed. The - invoke() method now returns the return value of the command.

    - -
  • -
  • The invoke() method of Pmw.TimeCounter now returns the return - value of the command.

    - -
  • -
  • Modified Pmw.ButtonBox to use the new (in Tk8.0) default option - of the Tkinter Button widget instead of a separate frame. - Changed default padding to be more compact. Removed "ring" frame - component and "ringborderwidth", "ringpadx" and "ringpady" - options. (Georg Mischler)

    - -
  • -
  • Changed 'pmw1' fontScheme to set default fonts only when running - under posix, since the default fonts on other systems look better.

    - -
-

10 December 1998

- -
  • Release of version 0.8

    - -
-

20 January 1999

- -
  • Added master option to Pmw.MegaToplevel and removed master - argument from the activate method.

    - -
  • -
  • Replaced rand module in demos with a simple random number - generator (since rand is not built-in on all versions of python).

    - -
-

22 February 1999

- -
  • Modified __init__.py so that it only accepts directories whose - names begin with Pmw_M_N and which have a /lib/PmwLoader.py/ - file.

    - -
-

13 May 1999

- -
  • Changed Pmw.ScrolledCanvas, Pmw.ScrolledText and Pmw.ScrolledListBox - to speed up scrolling if the scrollmodes are not both dynamic.

    - -
  • -
  • Changed busy cursor and activate/deactivate code so that it works - correctly under fast mouse clicking or fast keyboarding (using - accelerators). Also fixed so that grab is correctly restored - after a Pmw.ComboBox popup list is unmapped inside a modal dialog. - (Clemens Hintze)

    - -
  • -
  • Several dialogs now give focus to one of their components (listbox - or entry widget) when activated. (Clemens Hintze)

    - -
  • -
  • Fixed Pmw.ComboBox so that it unposts popup if the combobox is - unmapped and returns grab and focus correctly if destroyed.

    - -
  • -
  • Improved tracetk() output to be more readable. Also displays - nested calls to the Tk mainloop better and shows callbacks from - tcl to python.

    - -
  • -
  • Upgraded Blt support to blt2.4i. Graph widget is not backwards - compatible with blt2.1.

    - -
-

19 May 1999

- -
  • Fixed bug in Pmw.Balloon in placement of balloons over canvas - items when the canvas was scrolled. (Tessa Lau)

    - -
-

20 May 1999

- -
  • Added new Tk event types (new in Tk 8.0 and 8.0.5) to PmwBase - error display method. Also added check for unknown event types to - safeguard against future changes. (Magnus Kessler)

    - -
  • -
  • Added exclude argument to showbusycursor(). (Rob Hooft)

    - -
-

1 June 1999

- -
  • Added wrappers for Blt Stripchart and Tabset widgets. (Nick Belshaw)

    - -
  • -
  • Changed createcomponent() so that arguments to the constructor of - the component can now be specified as either multiple trailing - arguments to createcomponent() or as a single tuple argument.

    - -
-

7 June 1999

- -
  • Added call to update_idletasks() in Pmw.ScrolledCanvas, - Pmw.ScrolledFrame, Pmw.ScrolledText and Pmw.ScrolledListBox to - avoid endless mapping/unmapping of two dynamic scrollbars when the - window is first mapped and only one scrollbar is needed. - (Reported by Mark C Favas, solution suggested by Dieter Maurer.)

    - -
-

10 June 1999

- -
  • Fixed bug in bundlepmw.py when called with -noblt option. - (Reported by Kevin O'Connor)

    - -
  • -
  • Pmw.ComboBox now unposts the dropdown listbox before the selection - callback is invoked, to avoid problems when the callback takes a - long time to run. (Reported by Randall Hopper)

    - -
-

11 June 1999

- -
  • Release of version 0.8.1

    - -
-

29 June 1999

- -
  • PmwMessageBar.message() now replaces newlines with spaces before - displaying message. Also applies to helpmessage().

    - -
-

2 July 1999

- -
  • Improved toplevel window positioning under NT, and stopped most of - the ugly flashing.

    - -
-

5 July 1999

- -
  • The pmw1 fontScheme is now supported under NT, as is the size - option to Pmw.initialise().

    - -
-

6 July 1999

- -
  • Changed the names of positional arguments in the following - methods, so that they have less chance of conflicting with keyword - arguments: MegaArchetype.createcomponent(), ButtonBox.insert(), - ButtonBox.add(), MenuBar.addcascademenu(), MenuBar.addmenuitem() - and RadioSelect.add().

    - -
-

9 July 1999

- -
  • Added images and example code to the megawidget reference manuals. - (Suggested by Joerg Henrichs)

    - -
  • -
  • Fixed showbusycursor() under NT. It now calls update() instead of - update_idletasks() to force display of cursor. (Solution - suggested by George Howlett)

    - -
  • -
  • Improved display of arrows in ComboBox, Counter and TimeCounter.

    - -
-

16 July 1999

- -
  • Removed Pmw.maxfontwidth() function, since better functionality is - now supplied by the Tk "font measure" command.

    - -
  • -
  • Removed Pmw.fontexists() function, since in Tk8.0 all fonts exist.

    - -
-

28 July 1999

- -
  • Fixed bug in date counter with separator other than '/' and time - counter with separator other than ':'. (David M. Cooke, Alan - Robinson)

    - -
  • -
  • Under NT, the font named 'fixed' is not fixed width, so added - alias from 'Fixed' to 'Courier'.

    - -
  • -
  • Changed the bind() and tagbind() methods of Pmw.Balloon to - remove a potential memory leak. The methods now store the - funcids of the callback functions, so that if the same widget or - tag is bound twice, the balloon can remove the old bindings. - (Peter Stoehr)

    - -
  • -
  • Changed NoteBookR so that lowercmd, creatcmd and raisecmd are - called in that order when a page is selected. Also fixed bug - which always raised page 0 when notebook is resized. (Scott - Evans, Charles Choi)

    - -
-

1 August 1999

- -
  • Added dynamicGroups argument to defineoptions() method and - modified ButtonBox, MenuBar, PanedWidget, RadioSelect to register - their dynamic groups.

    - -
  • -
  • Pmw.initialise() can now be called multiple times, with - different root arguments, but only sequentially. Pmw does not - (yet) support multiple simultaneous interpreters. Modified - Pmw.EntryField so that it recreates class bindings when - Tkinter.root changes.

    - -
-

4 August 1999

- -
  • Added relmouse option to Pmw.Balloon. Fixed Pmw.Balloon so that - the balloon is not displayed off-screen. (Tessa Lau)

    - -
-

16 August 1999

- -
  • Added disableKeyboardWhileBusy option to initialise(). To ignore - keyboard input while displaying the busy cursor, Pmw sets the - focus for each toplevel window to the Blt busy window. However, - under NT, this causes each window to be raised. If this is not - acceptable, programs running on NT can request show/hidebusycursor - not to ignore keyboard input.

    - -
-

25 August 1999

- -
  • Added Pmw.Blt.busy_forget() and used it in Pmw.hidebusycursor() - when running under NT. There is a bug in the Blt busy release - command under NT where it sometimes fails to display the busy - cursor. Using busy forget avoids the problem.

    - -
-

27 September 1999

- -
  • Added busyCursorName option to Pmw.initialise() and added cursor - argument to Pmw.Blt.busy_hold(). (Mark Favas)

    - -
-

20 October 1999

- -
  • Replaced Pmw.NoteBookR and Pmw.NoteBookS with completely rewritten - Pmw.NoteBook.

    - -
  • -
  • Renamed Pmw.OptionMenu.get() to Pmw.OptionMenu.getcurselection() - and Pmw.PanedWidget.remove() to Pmw.PanedWidget.delete(), to be - more consistent with other megawidgets.

    - -
  • -
  • The index() method of several megawidgets now use Pmw.END, - Pmw.SELECT and Pmw.DEFAULT instead of strings, since these may - conflict with component names.

    - -
  • -
  • Pmw.OptionMenu.index() now uses Pmw.SELECT to return - index of the currently selected menu item, rather than None.

    - -
  • -
  • Added destroy() method to Pmw.MegaArchetype to handle cleaning up - of _hullToMegaWidget mapping.

    - -
  • -
  • Removed exclude argument from Pmw.showbusycursor() and added - Pmw.excludefrombusycursor() function instead. (Rob Hooft)

    - -
  • -
  • Fixed several bugs for Windows NT.

    - -
  • -
  • Added Pmw.ButtonBox.button() and Pmw.RadioSelect.button().

    - -
  • -
  • Added Pmw.Color.bordercolors().

    - -
-

21 October 1999

- -
  • Release of version 0.8.3. (Version 0.8.2 was not released.)

    - -
-

30 October 1999

- -
  • Added arrownavigation option and previouspage() and nextpage() - methods to Pmw.NoteBook. (Peter Funk)

    - -
  • -
  • Renamed the setnaturalpagesize() method of Pmw.NoteBook to - setnaturalsize() to be consistent with Pmw.PanedWidget.

    - -
  • -
  • Changed Pmw.excludefrombusycursor() to Pmw.setbusycursorattributes(). - Removed busyCursorName option from Pmw.initialise() and added - cursorName attribute to Pmw.setbusycursorattributes().

    - -
  • -
  • Added documentation source and build scripts to ftp site.

    - -
-

6 November 1999

- -
  • Fixed memory leaks when destroying megawidgets. Added automatic - check for memory leak to test script used by all tests. - Pmw.initialise() now uses a hook into Tkinter.Widget.destroy - rather than Tkinter.Frame.destroy to handle the case of - Pmw.NoteBook being destroyed (since the notebook hull is a canvas - and not a frame). Window manager delete protocol callbacks are - now cleaned up. Pmw.ScrolledListBox event bindings now do not - leak. (Reported by Jeff Weeks)

    - -
  • -
  • Removed key bindings for Pmw.ScrolledListBox except space and return keys.

    - -
-

20 November 1999

- -
  • Fixed bug in Pmw.Balloon when the canvas or text item that - triggered the balloon is deleted before the balloon is displayed - by the initwait timer. (Magnus Kessler)

    - -
  • -
  • Added 'nograb' to globalMode option of activate() method. (Rob Hooft)

    - -
  • -
  • Added __setitem__ method to Pmw.MegaArchetype, so that megawidget - options can be now set using megawidget['option'] = value style. - (Oliver Gathmann)

    - -
-

27 December 1999

- -
  • Converted from regex module to re module, since regex is not - implemented for Jpython. (Finn Bock)

    - -
-

30 December 1999

- -
  • Added clear() method to Pmw.ScrolledListBox (suggested by Carson - Fenimore).

    - -
-

15 March 2000

- -
  • Fixed problem in PmwBase when deleting windows that were created - before Pmw was initialised (such as splash windows displayed while - the application is coming up). (Mark Favas)

    - -
  • -
  • Added splash window to Pmw demo. (Mark Favas)

    - -
-

30 April 2000

- -
  • Added Pmw.MainMenuBar megawidget, which uses the menubar feature - of Tk to provide platform specific menu bars.

    - -
  • -
  • Fixed Pmw.Counter and several other megawidgets so that certain - hull constructor keywords, such as hull_relief and - hull_borderwidth, are not overriden in the constructor.

    - -
  • -
  • Thanks to Peter Cashin for his help on how to unpack gzipped tar - files on Microsoft Windows operating systems.

    - -
  • -
  • Added Pmw.HistoryText megawidget. This can be used as the basis - of an interactive text-based database query gui. It maintains a - history of each query and allows editing of prior queries.

    - -
  • -
  • Added references to the Pmw.Blt.Graph documentation by Bjørn Ove - Thue and Hans Petter Langtangen.

    - -
  • -
  • Searched for and fixed memory leaks. There are no more known memory leaks.

    -
    • For commands created by bind: these are cleaned up by Tkinter - when the widget is destroyed. Pmw.Balloon, which repeatedly - binds to the same widget (or item, using tag_bind), has been - fixed by passing the old command into the call to unbind or - tag_unbind which is cleaned up by Tkinter.

      - -
    • -
    • For commands created by class_bind: most class bindings are - only created once (per Tk interpreter) and so do not need to be - cleaned up. The exception is adding and deleting menus in - Pmw.MenuBar. This has now been fixed to clean up class_bind - commands when deleting menus.

      - -
    • -
    • Callbacks given to command, xscrollcommand, yscrollcommand, etc - options are cleaned up by Tkinter when the widget is destroyed. - Cases where Pmw repeatedly sets such options have now been fixed - to clean up the old command before configuring the new one. - These are in setitems in Pmw.OptionMenu and when modifying the - scrollcommand options in several of the scrolled widgets.

      - -
    • -
    • Pmw now cleans up calbacks it registers with the - WM_DELETE_WINDOW protocol for toplevel windows.

      - -
    - -
  • -
  • Added ManualTests.py to tests directory for tests which need to be - run by hand.

    - -
-

12 May 2000

- -
  • Release of version 0.8.4.

    - -
-

17 May 2000

- -
  • Modified Pmw.Counter to deal with the presence (python up to - 1.5.2) or absence (python 1.6 and after) of an L at the end of - the ascii representation of a long. (Mark Favas)

    - -
  • -
  • Fixed bug in Pmw.ScrolledFrame when given invalid flex options. - (Stephen D Evans)

    - -
-

23 January 2001

- -
  • Moved Pmw home from www.dscpl.com.au to pmw.sourceforge.net.

    - -
  • -
  • Added pmw2 font scheme, since the font used for balloon text with - pmw1 is too small on Linux.

    - -
  • -
  • Removed syntax coloring from code window in demos. It did not - look good and the pattern matching was not always correct.

    - -
  • -
  • Changed font size used for demos to 12 for Unix, since 14 looked - too big under Linux.

    - -
  • -
  • Minor fixes to tests for Tk 8.3.

    - -
-

8 February 2001

- -
  • Release of version 0.8.5

    - -
-

18 February 2001

- -
  • Added xview() and yview() methods to Pmw.ScrolledFrame (suggested - by Christer Fernstrom).

    - -
  • -
  • Made tktrace output more readable.

    - -
  • -
  • Added noBltBusy option to Pmw.initialise.

    - -
  • -
  • Fixed bug where combobox dropdown list could stay mapped after - entryfield was unmapped.

    - -
  • -
  • Improved scrolling in scrolled frame.

    - -
-

21 February 2001

- -
  • Fixed tests for recent version of Blt graph (reported by - Venkatesh Prasad Ranganath).

    - -
  • -
  • Fixed problem in Pmw.ScrolledFrame in python 1.5 - string.atof - does not accept a number as argument, but it does in python 2.0.

    - -
-

24 February 2001

- -
  • Modified Pmw.OptionMenu documentation to specify that list - elements must be strings (problem reported by Guy Middleton).

    - -
  • -
  • Fixed bug in Pmw.OptionMenu where the wrong item was displayed - when an integer item in the menu was selected with the mouse (even - though items should be strings).

    - -
  • -
  • Added work around to Pmw.ScrolledFrame for bug in Tk when - retrieving value from scrollbars soon after creation.

    - -
-

27 February 2001

- -
  • Added HistoryText and MainMenuBar to bin/bundlepmw.py - accidently - left out.

    - -
-

13 April 2001

- -
  • Changed default foreground (text) of Pmw.Balloown to black. (Eric - Pettersen)

    - -
  • -
  • Added default fontScheme to Pmw.initialise().

    - -
  • -
  • Added -fontscheme and -fontsize options to demo.

    - -
  • -
  • Added updatelayout() to Pmw.PanedWidget for use when dynamically - adding and deleting panes. (G Cash)

    - -
  • -
  • Added move() to Pmw.PanedWidget to move panes. (G Cash)

    - -
-

20 April 2001

- -
  • Fixed bug in Pmw.Balloon where the balloon would reappear if the - mouse button was pressed down inside a widget and then, while the - mouse button was being held down, the mouse was moved outside of - the widget and then moved back over the widget.

    - -
  • -
  • Fixed bug in Pmw.Balloon when destroying widgets while the balloon - was up. In this case, the balloon remained displayed even though - the widget had been destroyed. (Reported by Stefan Schone.)

    - -
  • -
  • Fixed bug in Pmw.Balloon when destroying widgets during the - initwait period. In this case, an error occurred when the - initwait timer went off when it tried to access the destroyed - widget. (Reported by Stefan Schone.)

    - -
  • -
  • Fixed Pmw.Balloon so that unbinding withdraws the balloon if - the widget being unbound is the widget which triggered the balloon.

    - -
  • -
  • Modified Pmw.Balloon so that when deleting a canvas or text item, - tagunbind() can be called which will withdraw the balloon if it - was triggered by the item. Unfortunately this can not be - automated as for widgets since Tk does not support <Destroy> - bindings on canvas or text items, so there is no way that - Pmw.Balloon can be notified of the deletion of an item.

    - -
  • -
  • Updated tests for python 2.1.

    - -
-

21 May 2001

- -
  • Pmw.OptionMenu now defaults to taking focus (on <Tab> key).

    - -
-

15 May 2002

- -
  • Fixed bug in Pmw.Graph.element_closest() where element names - should follow option arguments. (Val Shkolnikov)

    - -
-

5 June 2002

- -
  • Added command option to Pmw.TimeCounter.

    - -
  • -
  • Finished all documentation.

    - -
  • -
  • Fixed bug in documentation creation script which, since python - 2.0, printed default values of real options (such as the - horizfraction option of Pmw.ScrolledFrame) with too many digits - (such as 0.050000000000000003).

    - -
  • -
  • Fixed bug in setgeometryanddeiconify for cygwin python (John - Williams).

    - -
-

4 July 2002

- -
  • Added master option to MegaToplevel.show()

    - -
  • -
  • Improved MegaToplevel.show() so that tkraise is not called - unecessarily, thus avoiding 2 second delay under certain window - managers (such as sawfish) in most circumstances. There are still - problems with the Enlightenment window manager.

    - -
-

18 August 2002

- -
  • Added columnheader, rowheader and rowcolumnheader components to - Pmw.ScrolledText. (Rob Pearson)

    - -
  • -
  • Added getvalue() and setvalue() methods to several megawidgets - as a consistent way to set and get the user-modifiable state. - (Cimarron Taylor)

    - -
  • -
  • Made sub-classing simpler when no new options or components are - being created. A sub-class of a Pmw megawidget does not need to - have an __init__() method. If it does, it does not need to call - defineoptions(). Also, initialiseoptions() no longer requires an - argument (for backwards compatibility it may take an argument, but - it is ignored).

    - -
-

24 August 2002

- -
  • Release of version 1.0

    - -
-

26 August 2002

- -
  • Minor fixes.

    - -
  • -
  • Release of version 1.1

    - -
-

4 September 2002

- -
  • Added collapse, expand and toggle methods and collapsedsize option - to Pmw.Group. (Rob Pearson)

    - -
-

5 September 2002

- -
  • Added sticky option to several megawidgets.

    - -
-

18 September 2002

- -
  • Added appendtext method to Pmw.ScrolledText. (Graham Dumpleton)

    - -
-

26 September 2002

- -
  • Modified Pmw.ScrolledListBox to call dblclickcommand on - <Double-ButtonRelease-1> rather than <Double-ButtonPress-1> which - caused problems if the double button press unmapped the - ScrolledListBox. In this case, the second button release of the - double click is given to another widget. (Eric Pettersen)

    - -
-

14 June 2003

- -
  • Changes for python 2.3 and Tcl/Tk 8.4.2:

    -
    • Wrapped calls to cget() for Tkinter widgets in a call to - str(). Before python 2.3 cget() always returned a string. - Under python 2.3, Tkinter sometimes returns non-string values - (such as int, or Tcl_Obj). Made similar change when using - configure() to retrieve values. Fixed tests to handle integer - and Tcl_Obj return value from cget(). (Charles Doutriaux)

      - -
    • -
    • Fixed uses of col field of grid command. Must use full - column under Tcl/Tk 8.4.2.

      - -
    • -
    • Fixed PmwEntryField.py, PmwMessageBar.py, PmwScrolledField.py - so that the text is not greyed out under Tcl/Tk 8.4.2. This - was caused by a change in behaviour of the 'disabled' state - and the Tk entry widget. Now use new 'readonly' state for - Tcl/Tk 8.4.2.

      - -
    • -
    • Test script now ignores Blt test for Tcl/Tk 8.4.2, since it - causes Blt 2.4z to core dump. Blt needs to be fixed.

      - -
    • -
    • Changed Dialog test to work around problem caused by Tk 8.4.2 - enforcing transient behaviour of windows. When activate() is - called on a dialog whose parent is withdrawn, then the dialog - window is made transient. Under old versions of Tk, the - transient dialog was displayed, but under 8.4.2 the dialog is - not displayed. Work around is to deiconify parent of dialog.

      - -
    - -
-

5 August 2003

- -
  • Release of version 1.2

    - -
-

- - - -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home - -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/copyright.html b/Pmw/Pmw_1_2/doc/copyright.html deleted file mode 100644 index 0f5e7e8a..00000000 --- a/Pmw/Pmw_1_2/doc/copyright.html +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - Pmw copyright - - - - -

Pmw copyright

- -

- Copyright 1997-1999 Telstra Corporation Limited, Australia - Copyright 2000-2002 Really Good Software Pty Ltd, Australia

- -

Permission is hereby granted, free of charge, to any person - obtaining a copy of this software and associated documentation - files (the "Software"), to deal in the Software without - restriction, including without limitation the rights to use, copy, - modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions:

- -

The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software.

- -

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS IN THE SOFTWARE. -

- - - -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home - -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/counter1.gif b/Pmw/Pmw_1_2/doc/counter1.gif deleted file mode 100644 index 64efe355..00000000 Binary files a/Pmw/Pmw_1_2/doc/counter1.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/counter2.gif b/Pmw/Pmw_1_2/doc/counter2.gif deleted file mode 100644 index be894ed3..00000000 Binary files a/Pmw/Pmw_1_2/doc/counter2.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/demosandtests.html b/Pmw/Pmw_1_2/doc/demosandtests.html deleted file mode 100644 index d7190a3e..00000000 --- a/Pmw/Pmw_1_2/doc/demosandtests.html +++ /dev/null @@ -1,364 +0,0 @@ - - - - - - Pmw demonstrations and tests - - - - -

Pmw demonstrations and tests

- -

- -

- -

- Pmw comes with an extensive range of demonstrations and tests. The - demonstrations can be used to get a feel for what is provided by Pmw - and the demonstration code can be viewed to see examples of how to - use Pmw. The tests can be executed to check that there are no - problems with running Pmw in your environment. - -

- -
-

Demonstrations

-

- The Pmw demos directory contains demonstration scripts - showing many of the features of Pmw megawidgets. To view a - comprehensive package of all the demonstrations, including a view of - the source code, run the All.py script. Run - All.py -help for a short description of the script's - options. - -

- All of the demonstrations may also be run separately. Most of the - demonstrations show some of the features of one of the Pmw - megawidgets. For example, to see a demonstration of the ButtonBox - megawidget, change into the demos directory and - run - -

-
-
-
-python ButtonBox.py
-
-
-
- -

- Other demonstrations, which show other features of Pmw include -

-
-
-
-BltGraph.py         demonstrates the Pmw interface to
-                    the BLT graph and vector commands
-BltTabset.py        demonstrates the Pmw interface to
-                    the BLT tabset command
-Colors.py           how to set color schemes
-ConfigClass.py      how to configure the python class
-                    of a megawidger component
-ErrorHandling.py    how Pmw displays run time errors
-                    in a window
-ExampleDemo.py      template for new demonstrations
-Grid.py             the Tkinter Grid geometry manager
-LogicalFont.py      how to use standard values for fonts
-MessageInfo.py      how to extend the Pmw MegaToplevel
-                    class
-NestedDialogs.py    how nested modal dialogs behave
-Resources.py        how to use the option database to
-                    modify Tk widget option defaults
-Resources_Pmw.py    how to use the option database to
-                    modify megawidget option defaults
-ShowBusy.py         demonstrates the Pmw interface to
-                    the BLT busy command
-SpecialEntry.py     deriving from Pmw.EntryField
-Spectrum.py         some of the Pmw color handling
-                    functions
-SpeedTest.py        tests the speed of creating Pmw
-                    megawidgets
-TextDisplay.py      how to extend the Pmw MegaWidget
-                    class
-WidgetDestroy.py    megawidget destruction
-
-
-
- -Creating demonstrations of new megawidgets -
-

-If you create a new megawidget you can create a demonstration for it -by using the file -ExampleDemo.py as a -template. This template allows the demonstration to be run -individually or to be automatically included as part of the -demonstration package All.py. You should take a copy of -the template and name the new file after your megawidget. You should -then replace each instance of the word EXAMPLE with the -name of your megawidget and replace the code in the -__init__ method with code to create and initialise one or -more instances of your megawidget, which should be a child of -parent. You can add other methods as necessary. - -

- -
-

Tests

-

- The Pmw tests directory contains a test framework - and a set of test scripts for Pmw. - The tests cover the standard Tkinter module and most of the Pmw megawidgets. - The tests make a great - demonstration of the flexibility of the megawidgets. Simply change - into the tests directory and run - python All.py. - -

- If all tests pass there should be no output printed to standard - output. If any of the tests fail, please send the test output to - the maintainer at - gregm@iname.com. - -

- -

- All of the tests may be run separately. Most of the tests test the - features of one of the Pmw megawidgets. For example, to execute the - test for the ButtonBox megawidget, run - -

- -
-
-
-python ButtonBox_test.py
-
-
-
- -

- The Test.py file contains general testing functions and is imported - by all test files. - Other files, which test other features of Pmw include -

-
-
-
-Blt_test.py           BLT vector and graph interface
-Colors_test.py        setting color schemes
-MegaWidget_test.py    creation of megawidget classes
-Options_test.py       option and component handling
-PmwBase_test.py       more option and component handling
-Tkinter_test.py       Tk widgets in the Tkinter module
-
-
-
- -Creating tests for new megawidgets -
-

-If you create a new megawidget you should create a test for it. There -is no template file for creating tests, but by looking at the other -Pmw tests (for example, -ScrolledText_test.py) you -will get some idea of how to create a test for your megawidget. - -

- -

-The test files are designed to be run both individually or -automatically by the test package All.py. Each test file -must define the testData tuple. This consists of a -sequence of 2-element tuples, each tuple being a test specification -for one megawidget. Usually a file tests only one megawidget and so -there is only one test specification. The first element in the -specification is the megawidget class and the second is a sequence of -(yet more) 2-element tuples. In each of these tuples, the first -element is a sequence of individual tests to perform on an instance of -the megawidget and the second element is a dictionary to use for -the keyword arguments when creating the instance. Each individual -test is a tuple, the meaning of which depends on the type of the first -element, which may be either a string, a function or a method of the -megawidget class, as explained below. - -

- -
    -
  • -

    -If the first element is a string, then it is treated as an option of -the megawidget and configure() is called to set the option to the -value specified by the second element. After setting the option, -cget() is called to query the option. If the test tuple has three -elements, then the value returned by cget() must equal the value -specified by the third element. Otherwise, the value returned must -equal the value specified by the second element. For example, - -

    -
    -
    -
    -('vscrollmode', 'static'),
    -('text_relief', 'sunken'),
    -('vscrollmode', 'bogus', 'ValueError: bad vscrollmode ' +
    -  'option "bogus": should be static, dynamic, or none'),
    -
    -
    -
    - -
  • -
  • -

    -If the first element is a function or method, then the function or -method is called. The arguments to the call are given by the second -element. (As a special case, if the second element is not a tuple, it -is used as the only argument to the call.) The test tuple may have 2, -3 or 4 elements. - -

    -
      -
    • -

      -If it has two elements, then the value returned by the call must be -None. For example, - -

      -
      -
      -
      -(c.exportfile, '/tmp/ScrolledText_test.py'),
      -(os.unlink, '/tmp/ScrolledText_test.py'),
      -
      -
      -
      - -
    • -
    • -

      -If it has four elements, then the third element is a dictionary to use -for the keyword arguments in the call and the value returned by the -call must equal the value specified by the fourth element. For -example, - -

      -
      -
      -
      -(c.search, ('abc', '0.0'), {'nocase': 1}, '2.24'),
      -
      -
      -
      - -
    • -
    • -

      -If is has three elements and the third element is a dictionary, then -it is used for the keyword arguments in the call and the value -returned by the call must be None. For example - -

      -
      -
      -
      -(c.configurepane, 'first', {'size' : 200}),
      -
      -
      -
      - -
    • -
    • -

      -If is has three elements and the third element is not a dictionary, -then the value returned by the call must equal the value specified by -the third element. For example, - -

      -
      -
      -
      -(c.components, (), ['hull', 'label']),
      -(c.add, ('Legumes',),
      -  'ValueError: name "Legumes" already exists'),
      -
      -
      -
      - -
    • -
    -
  • -
- -

-Some special functions and values supplied by the Test module that may -be used in the tests include: -

-
-
-
-Test.callback       callback taking no arguments
-Test.callback1      callback taking one argument
-Test.callbackN      callback taking any number of arguments
-
-Test.currentWidget  returns the widget instance being tested
-Test.num_options    returns number of options for the widget
-
-Test.earthris       a sample Tkinter.PhotoImage
-Test.flagup         a sample Tkinter.BitmapImage
-Test.floatvar       a Tkinter.DoubleVar
-Test.stringvar      a Tkinter.StringVar
-
-
-
- -

- To slow down a test (to see what is being displayed), add the - following line which sets the delay between tests to (say) 1000 - milliseconds: - -

-
-
-
-Test.setdelay(1000)
-
-
-
- -

- To print information about what is being tested, add the line: - -

-
-
-
-Test.setverbose(1)
-
-
-
- -
-
- - -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home - -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/dynamicloader.html b/Pmw/Pmw_1_2/doc/dynamicloader.html deleted file mode 100644 index 01d701c3..00000000 --- a/Pmw/Pmw_1_2/doc/dynamicloader.html +++ /dev/null @@ -1,147 +0,0 @@ - - - - - - Dynamic loader - - - - -

Dynamic loader

- -

- There are two aspects of Pmw, unrelated to megawidgets, that - require special attention. Firstly, Pmw is made up of many - sub-modules, potentially making access to its various classes and - functions cumbersome for the user. Secondly, Pmw is regularly - being modified and added to, thus requiring the release of new - versions. Therefore, techniques for making access to the - sub-modules easy and efficient and for dealing with the different - versions have been developed. These techniques are incorporated - into the dynamic loader which Pmw creates when it is first - imported.

- -

The first purpose of the loader is to give access to all Pmw classes - and functions through a single entry point, the Pmw. prefix. For - example, to access the ComboBox class (which resides in one of the - sub-modules of Pmw), you just have to use Pmw.ComboBox. Without - the loader, this would be a more complicated reference, such as, - hypothetically, Pmw.PmwComboBox.ComboBox.

- -

The second purpose of the loader is to delay the importing of the - sub-modules until they are needed. This improves the startup time - of applications which only use a few Pmw megawidgets. It also - allows more megawidgets to be added to the library without slowing - down applications which do not use them.

- -

The third purpose of the loader is to allow a script using Pmw to - specify which version of Pmw it requires. This allows an - application to continue working correctly even after newer releases - of Pmw have been made which are not compatible with the version - expected by the application. Several versions of Pmw can be - installed at once, with the actual version used being specified by - each application. In addition, the loader can be configured to - search in one or more alpha versions of Pmw. These versions may - contain new megawidgets, or new versions of existing megawidgets, - that are currently not in the base releases.

- -

Several functions are available to set and query the version of - Pmw being used. These are Pmw.setversion() and - Pmw.setalphaversions() which specify the version and alpha - versions (if any) to use for this session; Pmw.version() which - returns the version(s) being used by this session; and - Pmw.installedversions() which returns the version(s) of Pmw - currently installed. These are described in the - Pmw functions reference manual.

- -

When Pmw is first imported, an instance of PmwLoader is created - and placed into sys.modules['Pmw']. From that point on, any - reference to attributes of the Pmw 'module' is handled by the - loader. The real Pmw package is stored in sys.modules['_Pmw'].

- -

The loader searches the Pmw package base directory for - sub-directories with the prefixes Pmw_ and Alpha_, which - contain Pmw base releases and alpha releases. The version numbers - are given by the part of the directory name following the prefix. - These versions are available for use and are those returned by the - Pmw.installedversions function. The initial version is set to - the base release with the greatest version number. When the first - reference to a Pmw class or function is made, the loader reads the - files named Pmw.def in the current base version directory and - also in the alpha directories (if any). These files list all the - classes and functions supported by the version. Pmw attributes - are first searched for in the alpha directories and then in the - base version directory. The first directory which supports the - reference is used. In this way, alpha versions override base - versions.

- -

The directory Alpha_99_9_example contains a simple example of - how to structure an alpha version. The following code can be used - to request that the alpha version be used and then creates an - instance of a new megawidget defined in the alpha version.

- -
 import Pmw
- Pmw.setalphaversions('99.9.example')
-
- # Create a standard message dialog using the base Pmw version.
- ordinary = Pmw.MessageDialog(
-     message_text = 'Ordinary\nPmw Dialog')
-
- # Create an example dialog using the alpha Pmw version.
- alpha = Pmw.AlphaExample()
- -

Freezing Pmw

- -

Since the dynamic loader requires that Pmw be installed at run - time, it can not be used when freezing Pmw. In this case, a - single module containing all Pmw code is required, which can then - be frozen with the rest of the application's modules. The - bundlepmw.py script in the Pmw bin directory can be used to - create such a file. This script concatenates (almost) all Pmw - megawidget files into a single file, Pmw.py, which it writes to - the current directory. The script is called like this:

- -
 bundlepmw.py [-noblt] [-nocolor] /path/to/Pmw/Pmw_X_X_X/lib
- -

The last argument should be the path to the lib directory of the - required version of Pmw. By default, the Pmw.py file imports - the PmwBlt and PmwColor modules and so, to freeze an - application using Pmw, you will need to copy the files PmwBlt.py - and PmwColor.py to the application directory before freezing.

- -

If you are sure that your application does not use any of the - Pmw.Blt or Pmw.Color functions, you can use the -noblt or - -nocolor options. In this case Pmw.py will be modified so - that it does not import these module(s) and so will not need to be - included when freezing the application.

- -

If your application only uses a few Pmw megawidgets, you can - remove the references to the usused ones in the files list in - the bundlepmw.py code. To make the change, take a copy of the - script and modify it. This will make the Pmw.py file smaller. - However, be sure that you do not delete megawidgets that are - components or base classes of megawidgets that you use.

- -

- - - -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home - -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/example.py b/Pmw/Pmw_1_2/doc/example.py deleted file mode 100644 index 0eed16fa..00000000 --- a/Pmw/Pmw_1_2/doc/example.py +++ /dev/null @@ -1,79 +0,0 @@ -import Tkinter -import Pmw - -class ThresholdScale(Pmw.MegaWidget): - """ Megawidget containing a scale and an indicator. - """ - - def __init__(self, parent = None, **kw): - - # Define the megawidget options. - optiondefs = ( - ('colors', ('green', 'red'), None), - ('threshold', 50, None), - ('value', None, Pmw.INITOPT), - ) - self.defineoptions(kw, optiondefs) - - # Initialise base class (after defining options). - Pmw.MegaWidget.__init__(self, parent) - - # Create the components. - interior = self.interior() - - # Create the indicator component. - self.indicator = self.createcomponent('indicator', - (), None, - Tkinter.Frame, interior, - width = 16, - height = 16, - borderwidth = 2, - relief = 'raised') - self.indicator.grid() - - # Create the scale component. - self.scale = self.createcomponent('scale', - (), None, - Tkinter.Scale, interior, - command = self._doCommand, - tickinterval = 20, - length = 200, - from_ = 100, - to = 0, - showvalue = 0) - self.scale.grid() - - value = self['value'] - if value is not None: - self.scale.set(value) - - # Check keywords and initialise options. - self.initialiseoptions() - - def _doCommand(self, valueStr): - if self.scale.get() > self['threshold']: - color = self['colors'][1] - else: - color = self['colors'][0] - self.indicator.configure(background = color) - -Pmw.forwardmethods(ThresholdScale, Tkinter.Scale, 'scale') - -# Initialise Tkinter and Pmw. -root = Pmw.initialise() -root.title('Pmw ThresholdScale demonstration') - -# Create and pack two ThresholdScale megawidgets. -mega1 = ThresholdScale() -mega1.pack(side = 'left', padx = 10, pady = 10) - -mega2 = ThresholdScale( - colors = ('green', 'yellow'), - threshold = 75, - value = 80, - indicator_width = 32, - scale_width = 25) -mega2.pack(side = 'left', padx = 10, pady = 10) - -# Let's go. -root.mainloop() diff --git a/Pmw/Pmw_1_2/doc/example1.gif b/Pmw/Pmw_1_2/doc/example1.gif deleted file mode 100644 index b54ca935..00000000 Binary files a/Pmw/Pmw_1_2/doc/example1.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/example2.gif b/Pmw/Pmw_1_2/doc/example2.gif deleted file mode 100644 index bd5889bd..00000000 Binary files a/Pmw/Pmw_1_2/doc/example2.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/exercises.py b/Pmw/Pmw_1_2/doc/exercises.py deleted file mode 100644 index edd4f521..00000000 --- a/Pmw/Pmw_1_2/doc/exercises.py +++ /dev/null @@ -1,123 +0,0 @@ -import Tkinter -import Pmw - -class ThresholdScale(Pmw.MegaWidget): - """ Megawidget containing a scale and an indicator. - """ - - def __init__(self, parent = None, **kw): - # Define the megawidget options. - optiondefs = ( - ('colors', ('green', 'red'), None), - ('orient', 'vertical', Pmw.INITOPT), - ('labelmargin', 0, Pmw.INITOPT), - ('labelpos', None, Pmw.INITOPT), - ('threshold', (50,), None), - ('value', None, Pmw.INITOPT), - ) - self.defineoptions(kw, optiondefs) - - # Initialise base class (after defining options). - Pmw.MegaWidget.__init__(self, parent) - - # Create the components. - interior = self.interior() - - # Create the indicator component. - self.indicator = self.createcomponent('indicator', - (), None, - Tkinter.Frame, interior, - width = 16, - height = 16, - borderwidth = 2, - relief = 'raised') - - # Create the value component. - self.value = self.createcomponent('value', - (), None, - Tkinter.Label, interior, - width = 3) - - # Create the scale component. - if self['orient'] == 'vertical': - # The default scale range seems to be - # the wrong way around - reverse it. - from_ = 100 - to = 0 - else: - from_ = 0 - to = 100 - - self.scale = self.createcomponent('scale', - (), None, - Tkinter.Scale, interior, - orient = self['orient'], - command = self._doCommand, - tickinterval = 20, - length = 200, - from_ = from_, - to = to, - showvalue = 0) - - value = self['value'] - if value is not None: - self.scale.set(value) - - # Use grid to position all components - if self['orient'] == 'vertical': - self.indicator.grid(row = 1, column = 1) - self.value.grid(row = 2, column = 1) - self.scale.grid(row = 3, column = 1) - # Create the label. - self.createlabel(interior, childRows=3) - else: - self.indicator.grid(row = 1, column = 1) - self.value.grid(row = 1, column = 2) - self.scale.grid(row = 1, column = 3) - # Create the label. - self.createlabel(interior, childCols=3) - - # Check keywords and initialise options. - self.initialiseoptions() - - def _doCommand(self, valueStr): - valueInt = self.scale.get() - colors = self['colors'] - thresholds = self['threshold'] - color = colors[-1] - for index in range(len(colors) - 1): - if valueInt <= thresholds[index]: - color = colors[index] - break - self.indicator.configure(background = color) - self.value.configure(text = valueStr) - -Pmw.forwardmethods(ThresholdScale, Tkinter.Scale, 'scale') - -# Initialise Tkinter and Pmw. -root = Pmw.initialise() -root.title('Pmw ThresholdScale demonstration') - -# Create and pack two ThresholdScale megawidgets. -mega1 = ThresholdScale(scale_showvalue = 1) -mega1.pack(side = 'left', padx = 10, pady = 10) - -mega2 = ThresholdScale( - colors = ('green', 'yellow', 'red'), - threshold = (50, 75), - value = 80, - indicator_width = 32, - scale_width = 25) -mega2.pack(side = 'left', padx = 10, pady = 10) - -# Create and pack two horizontal ThresholdScale megawidgets. -mega3 = ThresholdScale( - orient = 'horizontal', - labelpos = 'n', - label_text = 'Horizontal') -mega3.pack(side = 'top', padx = 10, pady = 10) -mega4 = ThresholdScale(orient = 'horizontal') -mega4.pack(side = 'top', padx = 10, pady = 10) - -# Let's go. -root.mainloop() diff --git a/Pmw/Pmw_1_2/doc/features.html b/Pmw/Pmw_1_2/doc/features.html deleted file mode 100644 index 055cce7b..00000000 --- a/Pmw/Pmw_1_2/doc/features.html +++ /dev/null @@ -1,87 +0,0 @@ - - - - - - Pmw features - - - - -

Pmw features

- -

- Pmw is a toolkit for building high-level compound widgets, or - megawidgets, constructed using other widgets as component parts. - It promotes consistent look and feel within and between graphical - applications, is highly configurable to your needs and is easy to - use.

- -

Pmw consists of:

-
  • A few base classes, providing a foundation for building - megawidgets.

    - -
  • -
  • A library of flexible and extensible megawidgets built on - the base classes, such as buttonboxes, notebooks, - comboboxes, selection widgets, paned widgets, scrolled - widgets and dialog windows.

    - -
  • -
  • A lazy importer/dynamic loader which is automatically - invoked when Pmw is first imported. This gives unified - access to all Pmw classes and functions through the Pmw. - prefix. It also speeds up module loading time by only - importing Pmw sub-modules when needed.

    - -
  • -
  • Complete reference documentation, covering all classes and - functions including all megawidgets and their options, - methods and components. Helpful tutorial material is also - available.

    - -
  • -
  • A test framework and tests for Pmw megawidgets.

    - -
  • -
  • A slick demonstration of the megawidgets.

    - -
  • -
  • An interface to the BLT busy, graph and vector commands.

    - -
- -

The interface to Pmw megawidgets is similar to basic Tk widgets, so it - is easy for developers to include both megawidgets and basic Tk - widgets in their graphical applications. In addition, Pmw - megawidgets may themselves be extended, using either inheritance or - composition.

- -

The use of the Pmw megawidgets replaces common widget combinations - with higher level abstractions. This simplifies code, making it - more readable and maintainable. The ability to extend Pmw - megawidgets enables developers to create new megawidgets based on - previous work.

- -

- - - -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home - -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/halfblueball.gif b/Pmw/Pmw_1_2/doc/halfblueball.gif deleted file mode 100644 index 6977920d..00000000 Binary files a/Pmw/Pmw_1_2/doc/halfblueball.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/howtobuild.html b/Pmw/Pmw_1_2/doc/howtobuild.html deleted file mode 100644 index 4a408b48..00000000 --- a/Pmw/Pmw_1_2/doc/howtobuild.html +++ /dev/null @@ -1,465 +0,0 @@ - - - - - - How to build Pmw megawidgets - - - - -

How to build Pmw megawidgets

- -

- -

- -
-

Introduction

-

- This document briefly describes how to design and code Pmw - megawidgets by inheriting from the Pmw base classes. It shows step - by step how to build a simple example megawidget. This megawidget - allows the user to select one of a range of numbers and it also - indicates if the selected number is greater than a given threshold. - -

- -
-

Choosing the components

- -

- The megawidget will be built using a Tkinter.Scale widget to allow - the user to select a number in a range, and a Tkinter.Frame widget - to act as an indicator, displaying red (say) if the selected number - exceeds the threshold. It will look something like this: - -

- -

- Scale 2 -

- -

- The programmer using this megawidget will need access to the scale - widget, since they will need to set the scale's range. Therefore - the scale will be made a component of the megawidget. The - programmer will probably not need access to the indicator frame, - but, just in case the need arises to change the borderwidth or - relief of the indicator, we will make it a component too. This - illustrates a convention about components - for maximum - configurability, make all sub-widgets components. - -

- -
-

Choosing the options

- -

- Apart from the component options now available through the scale and indicator - components, the megawidget will need a few options of its own. It - will need a threshold option to set the threshold. - It may also need options to set the colors of the indicator when the - selected value is both above and below the threshold. Other options - could be orient or indicatorpos to - specify the relative position of components and - margin, padx or - pady to specify spacing between and around the - components. For this example, we will define three options - - threshold, colors and - value. The colors option will be - a 2-element sequence specifying two colors (below threshold, above - threshold). The value option will be the initial - value of the scale. - -

- -
-

Coding the megawidget

- -

- The first things to do are to decide on a name for the new - megawidget, decide which base class to inherit from and to begin to - write the constructor. Most Pmw megawidgets are derived from either - Pmw.MegaWidget, Pmw.MegaToplevel or Pmw.Dialog. In this case, since - the widget is not to be contained within its own toplevel window, we - will inherit from Pmw.MegaWidget. The constructors of megawidgets - take one argument (the widget to use as the parent of the - megawidget's hull, defaulting to the root window) and any number of - keyword arguments. - -

- -
-class ThresholdScale(Pmw.MegaWidget):
-    """ Megawidget containing a scale and an indicator.
-    """
- 
-    def __init__(self, parent = None, **kw):
-
- -

- Next, we need to define the options supplied by this megawidget. - Each option is specified by a 3-element sequence. The first element - is the option's name. The second element is the default value. The - third element is either a callback function, - Pmw.INITOPT or None. In the first - case, the function is called at the end of construction (during the - call to self.inialiseoptions) and also - whenever the option is set by a call to - configure. Pmw.INITOPT indicates that - the option is an initialisation option - it cannot be set by calling - configure. None indicates that the - option can be set by calling configure, but that there - is no callback function. - -

- -

- The call to self.defineoptions also includes the - keyword arguments passed in to the constructor. The value given to - any option specified in the keywords will override the default - value. - -

- -
-        # Define the megawidget options.
-        optiondefs = (
-            ('colors',    ('green', 'red'), None),
-            ('threshold', 50,               None),
-            ('value',     None,             Pmw.INITOPT),
-        )
-        self.defineoptions(kw, optiondefs)
-
- -

- After defining the options, the constructor of the base class should - be called. The options need to be defined first so that a derived - class can redefine the default value of an option defined in a base - class. This is because the value specified by the derived class - must be made available before the base class constructor is called. - The keyword - arguments should not be passed into the base class constructor since - they have already been dealt with in the previous step. - -

- -
-        # Initialise base class (after defining options).
-        Pmw.MegaWidget.__init__(self, parent)
-
- -

- Now we should create the components. The components are created as - children (or grandchildren ...) of the megawidget's interior. - -

- -
-        # Create the components.
-        interior = self.interior()
-
- -

- The first component to create is the indicator. The - createcomponent method creates the sub-widget and - registers the widget as a component of this megawidget. It takes - five arguments plus any number of keyword arguments. The arguments - are name, aliases, group, class and constructor arguments. See the - Pmw.MegaArchetype reference manual) - for full details. - -

- -
-        # Create the indicator component.
-        self.indicator = self.createcomponent('indicator',
-                (), None,
-                Tkinter.Frame, (interior,),
-                        width = 16,
-                        height = 16,
-                        borderwidth = 2,
-                        relief = 'raised')
-        self.indicator.grid()
-
- -

- The scale component is created in a similar way. In this case, the - initial value of the scale is also set to the value of the - value initialisation option. - -

- -
-        # Create the scale component.
-        self.scale = self.createcomponent('scale',
-                (), None,
-                Tkinter.Scale, (interior,),
-                        command = self._doCommand,
-                        tickinterval = 20,
-                        length = 200,
-                        from_ = 100,
-                        to = 0,
-                        showvalue = 0)
-        self.scale.grid()
- 
-        value = self['value']
-        if value is not None:
-            self.scale.set(value)
-
- -

- At the end of the constructor, the initialiseoptions - method is called to check that all keyword arguments have been used - (that is, the caller did not specify any unknown or misspelled - options) and to call the option callback functions. - -

- -
-        # Check keywords and initialise options.
-        self.initialiseoptions()
-
- -

- All other methods must now be defined. In this case, only one - method is required - a method called whenever the scale changes and - which sets the indicator color according to the threshold. - -

- -
-    def _doCommand(self, valueStr):
-        if self.scale.get() > self['threshold']:
-            color = self['colors'][1]
-        else:
-            color = self['colors'][0]
-        self.indicator.configure(background = color)
-
- -

- To complete the megawidget, methods from other classes can be - copied into this class. In this case, all Tkinter.Scale methods - not already defined by the megawidget are made available as methods - of this class and are forwarded to the scale component. Note that - the third argument to Pmw.forwardmethods is the name of - the instance variable referring to the Tkinter.Scale widget and not - the name of the component. This function is called outside of and - after the class definition. - -

- -
-Pmw.forwardmethods(ThresholdScale, Tkinter.Scale, 'scale')
-
- -

- Important note: If a megawidget defines options - using defineoptions(), then this method must be - called in the megawidget constructor before the call to the base - class constructor and a matching call to - initialiseoptions() must made at the end of the - constructor. For example: - -

-
-    def __init__(self, parent = None, **kw):
-	optionDefs = ...
-	self.defineoptions(kw, optionDefs)
-	BaseClass.__init__(self, parent)
-	...
-	self.initialiseoptions()
-
- -
-

Creating instances of the megawidget

- -

- The code below creates two of our example megawidgets. The first is - created with default values for all options. The second is created - with new values for the options. It also redefines some of the - options of the components. - -

- -
-
-
-# Create and pack two ThresholdScale megawidgets.
-mega1 = ThresholdScale()
-mega1.pack(side = 'left', padx = 10, pady = 10)
-
-mega2 = ThresholdScale(
-        colors = ('green', 'yellow'),
-        threshold = 75,
-        value = 80,
-        indicator_width = 32,
-        scale_width = 25)
-mega2.pack(side = 'left', padx = 10, pady = 10)
-
-
-
- -

- Scale 1 -

- -
-

The complete code

- -

- The complete code for this example can be seen - here. - -

- -
-

Exercises

- -

- These exercises build on the example presented so far. - -

- -
    -
  1. - Change the call to create mega1 so that the scale - widget displays the current value next to the slider. (You may - need to look at the Tk scale manual page to find which option to - the scale component to set.) You will be able to - do this without modifying the ThresholdScale class code. - -
  2. -
  3. - Add a Tkinter.Label component between the indicator and scale - components. Modify the _doCommand method so that it - displays the current value of the scale in this label. - -
  4. -
  5. - Modify the colors and threshold - options so that they both accept a tuple. Now implement multiple - thresholds, so that the indicator displays one of several colors, - depending on the value of the scale. - -
  6. -
  7. - Add an orient initialisation option and lay out - the components horizontally or vertically depending on its value. - -
  8. -
  9. - Read the description of the createlabel() method in - the Pmw.MegaArchetype reference - manual and add labelpos and - labelmargin initialisation options which allow - the creation of a label for the megawidget. - -
  10. -
- -

- An example of how these changes can be made can be seen - here. - -

- -
-

Contributing your megawidgets to Pmw

- -

- If you have completed a megawidget that may be useful to others, you - may like to consider contributing it to Pmw. See - Contributions welcome for - how to contribute. - -

- -
-

Pmw coding conventions

- -

-As a final note, the Pmw code makes an attempt to follow these coding -conventions. -

- -
    -
  • - Class names: initial of each word is upper case (including first word). - -
  • -
  • - Public method and function names: all in lower case. - -
  • -
  • - Megawidget options: all in lower case. - -
  • -
  • - Megawidget component names: all in lower case. - -
  • -
  • - Function arguments: initial of each word is upper case (except first word). - -
  • -
  • - Private names: initial of each word is upper case (except first - word if not a class) - -
  • -
  • - Underscores as word separators are only used when overriding - Tkinter methods of same name. - -
  • -
  • - Indent is four spaces. - -
  • -
  • - Continuation lines are indented by eight spaces, so that they - won't be confused with a following nested code block. - Continuation lines should be used when a statement, which would - normally be written on one line, is longer than 80 characters. - Examples are "if" statements which contain many conditions and - function calls with many arguments. - -
  • -
  • - - Surround = with spaces when used with keyword - parameters in function calls. - -
  • -
  • - - Multi-line function calls should have one keyword parameter per - line. - -
  • -
-
-
- - -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home - -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/howtouse.html b/Pmw/Pmw_1_2/doc/howtouse.html deleted file mode 100644 index f7e43b92..00000000 --- a/Pmw/Pmw_1_2/doc/howtouse.html +++ /dev/null @@ -1,719 +0,0 @@ - - - - - - How to use Pmw megawidgets - - - - -

How to use Pmw megawidgets

- -

- -

- -
-

Introduction

-

- This document briefly describes the features of the Pmw megawidget - toolkit and how to use the megawidgets. Using examples, it - describes those features common to all Pmw megawidgets. For a - description of individual Pmw megawidgets see the - reference manuals. - For complete information on general Pmw megawidget functionality see the - Pmw.MegaArchetype reference manual. - For a lot more example code, run any of the files in the - Pmw demos directory. - -

- -

- A simple example of a megawidget is a counter. This widget - contains an entry field and two small arrow buttons. Users may - enter a value directly into the entry field or they may use the - buttons to increment and decrement the value displayed without - having to use the keyboard. Having this and other megawidgets in - your toolbox allows you to choose the best graphical interface for - your application. - -

-
-

Getting started

- -Initialisation of Pmw -
-

- To run the examples in the tutorial, make sure that the - Pmw lib directory is in sys.path. You - should be able to cut and paste the examples into an interactive - python session, or you can copy them to a file and run the file with - python. - -

-

- The following two lines should be entered before any of the - examples. These import and initialise Pmw. - For more information on Pmw.initialise() see the - Pmw functions reference manual. - -

- -
-
-
-import Pmw
-root = Pmw.initialise()
-
-
-
- -

- If necessary, you can have more control over how Tkinter and Pmw are - initialised by using this form of initialisation: - -

- -
-
-
-import Tkinter
-root = Tkinter.Tk()
-import Pmw
-Pmw.initialise(root)
-
-
-
- -
-

Megawidget construction

- -Creating a counter -
-

- Now that you have the formalities out of the way, you can create and - pack a counter megawidget (see - Pmw.Counter reference manual) using - its default configuration like this: - -

- -
-
-
-counter1 = Pmw.Counter()
-counter1.pack(padx = 10, pady = 10)
-
-
-
- -

- Now enter a number and click on the arrow buttons to see the number - increment or decrement. The result looks something like this: - -

- -

- Counter 1 -

- -

- The above example creates the counter as a child of the root window. - If you want to create it as a child of another window (for example, - a Tkinter.Frame widget called 'frame'), add the parent as an - argument to the constructor: - -

- -
-
-
-counter1a = Pmw.Counter(frame)
-
-
-
- -
-

Methods

-

- Once a megawidget has been created, you can call any of its other - methods in a similar way to Tk widgets. The following sets the value - of the counter and then increments it: -

- -
-
-
-counter1.setentry(41)
-counter1.increment()
-
-
-
- -
-

Options

-

- Like any widget, a megawidget may have options to allow it to be - configured for a particular use. Options allow the megawidget user - to modify the appearance and behaviour of the megawidget. The - counter megawidget has several such options. One of them, - datatype, specifies how the counter should count up - and down, such as, for example, by integers, reals, times or dates. - The default value is 'numeric', which means the - counter expects integers to be entered and will support - incrementing and decrementing by whole numbers. - -

- -

- Another option is - increment, which specifies how many units should be - added or subtracted when the counter is incremented or decremented. - Using these options, you can create a time counter, supporting the - format HH:MM:SS, and counting in minutes, like - this (note also the call to the setentry method to set - the contents of the entry field): - -

- -
-
-
-counter2 = Pmw.Counter(
-    datatype = 'time',
-    increment = 60)
-counter2.setentry('00:00:00')
-counter2.pack(padx = 10, pady = 10)
-
-
-
- -

- Many megawidget options can be modified using the - configure() method. For example, you can change the - value of the increment option to 10 minutes like - this: - -

- -
-
-
-counter2.configure(increment = 60 * 10)
-
-
-
- -Initialisation options -
-

- Some megawidget options can only be set when creating the megawidget. - These options can not be set by calling the configure() - method, but they can be queried in all the usual ways. For example, - the counter has an orient initialisation option - which specifies whether the arrow buttons should appear to the - left and right of the entry field ('horizontal') - or above and below ('vertical'). You can create a - numeric counter with arrow buttons above and below the entry - field like this: - -

- -
-
-
-counter3 = Pmw.Counter(orient = 'vertical')
-counter3.pack(padx = 10, pady = 10)
-
-
-
- -Querying options -
-

- You can query the value of megawidget options (initialisation or - not) in similar ways as for normal Tkinter widgets. For example, - the following code prints the values of some of the counter options. - -

- -
-
-
-print counter3.cget('increment')
-    --> 1
-print counter3.configure('orient')
-    --> ('orient', 'orient', 'Orient', 'horizontal', 'vertical')
-
-
-
- -

- When a Tk widget option is queried, its value is always - returned as a string, regardless of the type used when setting the - option. However, when a Pmw megawidget option is queried, a - reference to the object used when setting the option is returned. - In other words it is not always a string. For example, the type - returned by cget('increment') above was integer. - -

- -
-

Components

-

- Megawidgets are made up of other widgets, which we call - components. Each component is known by a logical name and - may be either a simple Tk widget, or may itself be a megawidget. - Pmw gives the megawidget user access to not only the functionality - supported directly by the megawidget through its options and methods, - but also to the components of the megawidget and their options and - methods. To access a component directly, use the - component() method. For example, to call method - doit of component comp - of megawidget mega: - -

- -
-
-
-mega.component('comp').doit()
-
-
-
- -Component options -
-

- There is a short-hand way to access the options of components, by - using the notation component_option. This allows, for - example, a counter megawidget to be configured with different - colored backgrounds for each of its arrow button components (these - components are called downarrow and - uparrow): - -

- -
-
-
-counter2.configure(
-    downarrow_background = 'green',
-    uparrow_background = 'red')
-
-
-
- -The hull -
-

- All megawidgets are enclosed in a containing widget which is created - automatically by the Pmw base classes. For normal megawidgets the - container is a Tkinter Frame widget. For megawidgets which are - toplevel windows, the container is a Tkinter Toplevel widget. The - containing widget is accessible as the hull - component. - -

- -

- To access options of the containing widget use the form - hull_option. For example to create a - counter megawidget with a wide sunken border around it: - -

- -
-
-
-counter4 = Pmw.Counter(
-    hull_relief = 'sunken',
-    hull_borderwidth = 5 
-)
-
-
-
- - -The interior -
-

- Some megawidgets, such as Dialog and LabeledWidget, also have a - frame into which users can pack other widgets. This frame may be a - component but can also be accessed with the interior() - method. For the Pmw.MegaToplevel and Pmw.MegaWidget classes, the - interior widget is the same as the hull widget. For other - megawidgets, the hull is the outer, containing widget and the - interior is the empty frame which can be used to extend the - megawidget by including extra internal widgets. - -

- -Sub components and aliases -
-

- Components may themselves be megawidgets and so their - (sub-)components can be referred to using the notation - component_sub-component. For example, the - entryfield component of the counter is a - Pmw.EntryField megawidget (which handles the input validation). In - turn, this has a Tkinter.Entry component named - entry. Therefore, you can change the background of - the counter's Tkinter.Entry widget with: - -

- -
-
-
-counter2.configure(entryfield_entry_background = 'yellow')
-
-
-
- -

- Most component path names (like entryfield_entry) - have a shorter alias defined for them. In this - case, you can use the equivalent: - -

- -
-
-
-counter2.configure(entry_background = 'yellow')
-
-
-
- -Changing the python class of a component -
-

- Each megawidget component is an instance of some python class. The - default class of each component is given in the reference manual. - By using the special pyclass component option, you - can specify a different python class to use when creating the - component. For example, to create a Pmw.Counter megawidget which - has a Tkinter.Button as its label, rather than the default - Tkinter.Label: - -

- -
-
-
-counter5 = Pmw.Counter(
-        labelpos = 'w',
-        label_text = 'Hello',
-        label_pyclass = Tkinter.Button
-)
-
-
-
-
- -
-

Forwarding methods

-

- Since a Pmw megawidget is a normal python class, it both inherits - methods from its base classes and also may have other methods - defined for it in the usual way. - Pmw also supports a third way that a megawidget may gain methods - - by 'forwarding' methods to one or more of its subwidgets. This is - also known as 'delegating'. - For example, a Pmw.Counter megawidget delegates the methods related - to its Pmw.EntryField component, entryfield, to the - component. It does not have to explicitely define methods which - call the component methods. - This is why we can call counter2.setentry() - since - setentry() is a method of the Pmw.EntryField - component, it is available to the Pmw.Counter. - -

-

- Methods already defined by a class or its base classes take - precedence over delegated methods. For example, Pmw.Counter - inherits a cget method from Pmw.MegaArchetype. - Therefore, this method is not delegated to the cget - method of Pmw.EntryField. - -

- -
-

Extending Pmw megawidgets

- -

- There are several ways of extending Pmw megawidgets. Firstly, the - flexibility of the options and components allows the widget's - appearance and behaviour to be greatly modified. Secondly, widgets - of the user's choice can be added inside some megawidgets by using - the interior() method. The Pmw classes MegaToplevel, MegaWidget, - Dialog and LabeledWidget are particularly designed to be extended in - this way. For example, to create a dialog window containing a - counter: - -

- -
-
-
-dialog = Pmw.Dialog(
-        title = 'Counter dialog',
-        buttons = ('OK', 'Cancel'))
-interior = dialog.interior()
-counter = Pmw.Counter(interior)
-counter.pack(padx = 20, pady = 20)
-
-
-
- -

- Counter 2 -

- -

- A third way to extend megawidgets is to inherit from (or subclass) - them. See How to build Pmw - megawidgets for information on how to use inheritance to extend - a megawidget by adding new options. For simpler cases, where new - methods are to be added to an existing megawidget and/or the default - values for some options are to be changed, normal subclassing can be - used. For example, to create new classes based on a Pmw.Counter, - one with a new method getminutes() and one with a - default datatype of 'time' and a white entry background: - -

- -
-
-
-class MinuteCounter1(Pmw.Counter):
-
-    def getminutes(self):
-	return Pmw.timestringtoseconds(self.getvalue()) / 60
-
-class MinuteCounter2(Pmw.Counter):
-
-    def __init__(self, parent = None, **kw):
-        kw['datatype'] = 'time'
-        kw['entry_background'] = 'white'
-        kw['entryfield_value'] = '00:00:00'
-        kw['increment'] = 60
-	apply(Pmw.Counter.__init__, (self, parent), kw)
-
-
-
- -
-

A quick example

-

- The following code is a small example of how to use Pmw megawidgets. - It is a complete program which displays three ways for the user to - enter a value - using an up-down counter, an entry field with - validation and a dropdown combobox. - -

-
-
-
-import Pmw
-root = Pmw.initialise(fontScheme = 'pmw1')
-
-counter = Pmw.Counter(
-        label_text = 'Counter:',
-        labelpos = 'w',
-        entryfield_value = '00:00:00',
-        entryfield_validate = 'time',
-        datatype='time',
-        increment=5*60,
-)
-counter.pack(fill = 'x', padx = 10, pady = 10)
-
-entry = Pmw.EntryField(
-        label_text = 'Real entry:',
-        labelpos = 'w',
-        value = '+2.9979e+8',
-        validate = 'real',
-)
-entry.pack(fill = 'x', padx = 10, pady = 10)
-
-combo = Pmw.ComboBox(
-        label_text = 'ComboBox:',
-        labelpos = 'w',
-        scrolledlist_items = map(str, range(20))
-)
-combo.pack(fill = 'x', padx = 10, pady = 10)
-
-# Make the labels line up neatly
-Pmw.alignlabels((counter, entry, combo))
-
-root.title('Pmw megawidgets example')
-root.mainloop()
-
-
-
- -

- Example 1 -

- -
-

Another example

-

- The following also shows how to use Pmw megawidgets. It displays a - RadioSelect megawidget and an exit button packed into the root - window. - -

- -
-
-
-import Tkinter
-import Pmw
-
-def callback(tag):
-    # This is called whenever the user clicks on a
-    # button in the RadioSelect widget.
-    print tag, 'was pressed.'
-
-# Initialise Tkinter and Pmw.
-root = Pmw.initialise(fontScheme = 'pmw1')
-root.title('Pmw RadioSelect demonstration')
-
-# Create and pack a RadioSelect widget.
-radio = Pmw.RadioSelect(
-        command = callback,
-        labelpos = 'w',
-        label_text = 'Food group:')
-radio.pack(padx = 20, pady = 20)
-
-# Add some buttons to the RadioSelect.
-for text in ('Fruit', 'Vegetables', 'Cereals', 'Legumes'):
-    radio.add(text)
-radio.invoke('Vegetables')
-
-# Create an exit button.
-exit = Tkinter.Button(text = 'Exit', command = root.destroy)
-exit.pack(pady = 20)
-
-# Let's go.
-root.mainloop()
-
-
-
- -

- Example 2 -

- -
-

Using the Tk option database

-

- There are several ways to use the Tk option database to customise a - Pmw application. Firstly you can customise all the basic Tk widgets - in the usual way. For example, to set the background of all - Tkinter.Label widgets (whether a megawidget component or not): - -

- -
-
-
-root.option_add('*Label.background', 'pink')
-
-
-
- -

- To set the background of all Pmw.EntryField label - components: - -

- -
-
-
-root.option_add('*EntryField.Label.background', 'green')
-
-
-
- -

- To set the background of all Pmw.EntryField components, including - the hull component: - -

- -
-
-
-root.option_add('*EntryField*background', 'blue')
-
-
-
- -

- The above option settings affect basic Tk widgets and, since it is - built into the Tk widgets, this functionality is always available. - However, to be able to use the Tk option database to set the default - values for Pmw megawidget options, Pmw.initialise() - must be called with useTkOptionDb = 1. If this is not - done, Pmw does not query the Tk option database for megawidget - option defaults. This is the default behaviour because there is a - slight performance penalty for using the Tk option database. - -

- -

- Assuming useTkOptionDb has been set, the default - buttonbox position of all Pmw.Dialog megawidgets can be changed - with: - -

- -
-
-
-root.option_add('*Dialog.buttonboxpos', 'e')
-
-
-
- -

- To set the label position of all Pmw.EntryField megawidgets, thus giving - them a label component by default: - -

- -
-
-
-root.option_add('*EntryField.labelpos', 'w')
-
-
-
- -
-
- - -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home - -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/index.html b/Pmw/Pmw_1_2/doc/index.html deleted file mode 100644 index ef531a23..00000000 --- a/Pmw/Pmw_1_2/doc/index.html +++ /dev/null @@ -1,131 +0,0 @@ - - - - - - Pmw megawidgets 1.2 - - - - -

Pmw 1.2

- -

Python megawidgets

- -

- -

- -

-Pmw is a toolkit for building high-level compound widgets in Python -using the Tkinter module. -

- -

-It consists of a set of base classes and a library of -flexible and extensible megawidgets built on this foundation. These -megawidgets include notebooks, comboboxes, selection widgets, paned -widgets, scrolled widgets, dialog windows, etc. - -

- -

-Local documentation -

- -
-
- - - Main features -
- Getting started - including downloading - and installation -
- How to use Pmw megawidgets - creating - and configuring megawidgets -
- How to build Pmw megawidgets - inheriting - (sub-classing) from Pmw megawidgets -
- Demonstrations and tests - how to run -
- Dynamic loader - also discusses how - to "freeze" Pmw -
- Reference manuals - complete documentation - of all Pmw classes and functions -
- Porting between different versions of Pmw -
- Change log -
- Todo list and list of known bugs -
- Copyright -
-
- -

-External links -

- -
-
- - - Pmw project home page - on SourceForge - contains CVS source repository, bug tracking, - release distributions, mailing list, etc - -
- Pmw-general - mailing list - subscribe to this list to get announcements of - Pmw releases and general discussion on Pmw - -
- A User's Guide - to Pmw.Blt - - an excellent tutorial and reference covering the Pmw interface - to the powerful Blt graph widget, written by Bjørn Ove Thue - and Hans Petter Langtangen. You can also download the full - HTML document for local viewing. - -
-
- -

-See the -Pmw megawidgets home page -for the latest information about Pmw. - -

- -

- -Comments, bugs, fixes to the Pmw -discussion and announcement mailing list. - -

- - -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/porting.html b/Pmw/Pmw_1_2/doc/porting.html deleted file mode 100644 index 64a7cb5d..00000000 --- a/Pmw/Pmw_1_2/doc/porting.html +++ /dev/null @@ -1,325 +0,0 @@ - - - - - - Porting between different versions of Pmw - - - - -

Porting between different versions of Pmw

- -

- This document contains a brief guide to porting existing code - between different versions of Pmw. It includes significant - functionality changes but does not include bug fixes or compatible - enhancements. For details of all changes, see - Changes to Pmw versions.

- -

Porting from 0.8.5 to 1.0, 1.1 and 1.2

- -
  • Bug fix, documention and new features only. No - backwards-incompatible changes.

    - -
-

Porting from 0.8.4 to 0.8.5

- -
  • Bug fix release only. No interface changes.

    - -
-

Porting from 0.8.3 to 0.8.4

- -
  • Change the setnaturalpagesize() method of Pmw.NoteBook to - setnaturalsize() (to be consistent with Pmw.PanedWidget).

    - -
  • -
  • Change Pmw.excludefrombusycursor() to Pmw.setbusycursorattributes(). - Replace busyCursorName option of Pmw.initialise() with - cursorName attribute of Pmw.setbusycursorattributes().

    - -
  • -
  • Several rarely used key bindings for Pmw.ScrolledListBox were - removed, changing the behaviour of the megawidget.

    - -
-

Porting from 0.8.1 to 0.8.3

- -
  • The megawidgets Pmw.NoteBookR and Pmw.NoteBookS have been - replaced by a new Pmw.NoteBook. The interfaces are not - compatible, so see the Pmw.NoteBook reference manual for - details.

    - -
  • -
  • Change the get() method of Pmw.OptionMenu to getcurselection() - and the remove() method of Pmw.PanedWidget to delete().

    - -
  • -
  • If you use 'end', 'default' or None in calls to the - index() method of several megawidgets, change these to - Pmw.END, Pmw.DEFAULT and Pmw.SELECT, respectively.

    - -
  • -
  • The exclude argument has been removed from Pmw.showbusycursor(). - Use Pmw.excludefrombusycursor() instead.

    - -
  • -
  • The names of some of the positional arguments in the following - methods have changed: MegaArchetype.createcomponent(), - ButtonBox.insert(), ButtonBox.add(), MenuBar.addcascademenu(), - MenuBar.addmenuitem() and RadioSelect.add().

    - -
  • -
  • The Pmw.maxfontwidth() function has been removed. Use the - font_measure() Tkinter method, or if that has not yet been - implemented:

    -
     someWidget.tk.call('font', 'measure', someFont, 'W')
    - - -
  • -
  • The Pmw.fontexists() function has been removed. This is - because, since Tk8.0, all fonts exist, so it no longer has - any meaning.

    - -
-

Porting from 0.8 to 0.8.1

- -
  • The Blt.Graph now supports blt2.4i which is not backwards - compatible with blt2.1.

    - -
-

Porting from 0.7 to 0.8

- -
  • The format argument of Pmw.datestringtojdn() now defaults to - 'ymd'. If you want to display dates with year, month and day - in a different order, add a format option to - Pmw.datestringtojdn() or to the datatype option of Pmw.Counter - or the validate option of Pmw.EntryField.

    - -
  • -
  • The justify() method from Pmw.ScrolledListBox has been removed. - Use the xview() or yview() methods instead.

    - -
  • -
  • Replace the getFrame() method of Pmw.ScrolledFrame with the - interior() method.

    - -
  • -
  • Replace the ringpadx and ringpady options of Pmw.Group by - padding the megawidget itself or by padding the children of the - megawidget.

    - -
  • -
  • Replace the canvasbind() and canvasunbind() methods of - Pmw.Balloon with tagbind() and tagunbind().

    - -
  • -
  • The return value of Pmw.EntryField command callback is now - ignored. Previously, if the callback destroyed the megawidget, - it was required to return the string 'break', to work around a - problem in the event handling mechanism in Tkinter. With python - 1.5.2, Tkinter has been fixed. Therefore, user-supplied - callback functions should use Pmw.hulldestroyed to check if the - megawidget has been destroyed before performing any operations - on it.

    - -
  • -
  • If you require the 'pmw1' fontScheme when running under - Microsoft Windows and Macintosh, you will need to set the Tk - font options manually.

    - -
-

Porting from 0.6 to 0.7

- -
  • Replace the maxwidth option of Pmw.EntryField with the 'max' - field of the validate option.

    - -
  • -
  • To specify that there should be no validation performed for a - Pmw.EntryField, the validate option must be None, not '' as - before.

    - -
  • -
  • The date and time values of the Pmw.EntryField validate option - (such as 'date_dmy' and 'time24', etc) are no longer supported. - Instead use a dictionary as the value of the validate option - with 'date' or 'time' in the 'validator' field. Include - other fields in the dictionary to further specify the - validation.

    - -
  • -
  • Pmw.Counter no longer supports the old date and time values for - the datatype option. Use a dictionary with a 'counter' - field of 'date' or 'time' and other fields to further - specify the counting.

    - -
  • -
  • Pmw.Counter no longer supports the min and max options. Use - the Pmw.EntryField validate option instead.

    - -
  • -
  • The bbox method of Pmw.ScrolledListBox now refers to the bbox - method of the listbox component, not the hull component.

    - -
  • -
  • By default, Pmw.MenuBar now automatically adds hotkeys to menus - and menu items for keyboard traversal. To turn this off, use the - hotkeys = 0 option.

    - -
  • -
  • The createcomponent() method now disallows the creation of - component names containing an underscore. If any component - names contain an underscore, rename them.

    - -
-

Porting from 0.5 to 0.6

- -

To port applications using Pmw version 0.5 to version 0.6, make - sure you are using python1.5. Then, simply change any lines in - your application like this:

- -
 from PmwLazy import Pmw
- -

to this:

- -
 import Pmw
- -

Also, if you have added the lib directory of a specific version - of Pmw to sys.path or PYTHONPATH, this can be removed, as long - as Pmw can now be found from the default path, such as in the - python site-packages directory.

- -

Porting from 0.2 to 0.4

- -
  • To get Pmw.0.2 default fonts (helvetica with bold italic menus - and italic scales) initialise with:

    -
     Pmw.initialise(fontScheme = 'pmw1')
    - -

    If no fontScheme is given, the standard Tk default fonts are used.

    - - -
  • -
  • Remove all calls to setdefaultresources(), usual(), keep(), - renameoptions(), ignore() and defineoptiontypes().

    - -
  • -
  • Move call to defineoptions() to before call to base class - constructor, create optiondefs tuple from self.defineoptions - arguments, then call defineoptions().

    - -
  • -
  • Remove resource class and name from optiondefs.

    - -
  • -
  • The last element in the optiondefs tuple (callback function) - must be given (may be None).

    - -
  • -
  • Add to classes currently without any options:

    -
     optiondefs = ()
    - self.defineoptions(kw, optiondefs)
    - - -
  • -
  • Use createcomponent() to create components - this replaces the - calls to the component widget constructor and to - registercomponent().

    - -
  • -
  • Do not inherit from Pmw.LabeledWidget. Instead, replace with - Pmw.MegaWidget with labelpos and labelmargin options and a call - to self.createlabel(). If calling createlabel(), must replace - pack() with grid().

    - -
  • -
  • When calling a megawidget constructor, include subcomponent name when - setting subcomponent options (eg labeltext -> label_text)

    - -
  • -
  • The items option of ScrolledListBox is an initialisation option - only - use setlist() method after initialisation.

    - -
  • -
  • The autorelief option for Counter, EntryField, ScrolledText, - TextDialog has been removed.

    - -
  • -
  • ScrolledListBox.getcurselection() always returns a tuple of strings, - possibly of zero length.

    - -
  • -
  • Counter increment is always initialised to 1.

    - -
  • -
  • The 'time' Counter datatype option has been replaced by - 'timeN' and 'time24'.

    - -
  • -
  • The 'time' EntryField validate option has been replaced by - 'timeN' and 'time24'.

    - -
  • -
  • Replace call to initialise() with initialiseoptions(), removing - "kw" arg. This should always be the last line in a megawidget - constructor.

    - -
  • -
  • Replace hide() with withdraw().

    - -
  • -
  • Now need iconpos option for MessageDialogs with icon_bitmap option set.

    - -
  • -
  • Example megawidget class definition:

    - -
-
class MyBigWidget(Pmw.MegaWidget):
-    def __init__(self, parent = None, **kw):
-
-        # Define the megawidget options.
-        optiondefs = (
-            ('errorbackground',   'pink',      None),
-            ('maxwidth',          0,           self._myfunc),
-            ('myinit',            'good',      Pmw.INITOPT),
-        )
-        self.defineoptions(kw, optiondefs)
-
-        # Initialise the base class (after defining the options).
-        Pmw.MegaWidget.__init__(self, parent)
-
-        # Create the components.
-        interior = self.interior()
-        self._widget = self.createcomponent('component',
-                (('alias', 'component_alias'),), None,
-                Tkinter.Button, (interior,))
-        self._widget.grid(column=0, row=0, sticky='nsew')
-
-        self.createlabel(interior)
-
-        # Initialise instance variables.
-        self.deriveddummy = None
-
-        # Check keywords and initialise options.
-        self.initialiseoptions(MyBigWidget)
-
- - - -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home - -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/refindex.html b/Pmw/Pmw_1_2/doc/refindex.html deleted file mode 100644 index 19a549e0..00000000 --- a/Pmw/Pmw_1_2/doc/refindex.html +++ /dev/null @@ -1,79 +0,0 @@ - - - - - - Pmw reference manual index - - - - -

Pmw reference manual
index

- - -

- -

- -
Base classes
-Pmw.MegaArchetype -Pmw.MegaWidget -Pmw.MegaToplevel -
-
Widgets
-Pmw.ButtonBox -Pmw.ComboBox -Pmw.Counter -Pmw.EntryField -Pmw.Group -Pmw.HistoryText -Pmw.LabeledWidget -Pmw.MainMenuBar -Pmw.MenuBar -Pmw.MessageBar -Pmw.NoteBook -Pmw.OptionMenu -Pmw.PanedWidget -Pmw.RadioSelect -Pmw.ScrolledCanvas -Pmw.ScrolledField -Pmw.ScrolledFrame -Pmw.ScrolledListBox -Pmw.ScrolledText -Pmw.TimeCounter -
-
Dialogs
-Pmw.AboutDialog -Pmw.ComboBoxDialog -Pmw.CounterDialog -Pmw.Dialog -Pmw.MessageDialog -Pmw.PromptDialog -Pmw.SelectionDialog -Pmw.TextDialog -
-
Miscellaneous
-Pmw.Balloon -Pmw.Blt -Pmw.Color -Module functions -
- -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home - -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/scale1.gif b/Pmw/Pmw_1_2/doc/scale1.gif deleted file mode 100644 index 5cf5d60b..00000000 Binary files a/Pmw/Pmw_1_2/doc/scale1.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/scale2.gif b/Pmw/Pmw_1_2/doc/scale2.gif deleted file mode 100644 index 5682715e..00000000 Binary files a/Pmw/Pmw_1_2/doc/scale2.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/doc/starting.html b/Pmw/Pmw_1_2/doc/starting.html deleted file mode 100644 index be447450..00000000 --- a/Pmw/Pmw_1_2/doc/starting.html +++ /dev/null @@ -1,382 +0,0 @@ - - - - - - Getting started with Pmw - - - - -

Getting started with Pmw

- -

- -

- -
-

Introduction

-

-This document describes how to fetch and install Pmw, and how to run -the demonstrations and tests. - -

- -
-

Requirements

-

-Pmw.1.2 requires the _tkinter and Tkinter modules. It works -with python versions 1.5.2 and greater (tested up to 2.2.1) and Tk -versions 8.0 and greater (tested up to 8.3.2). - -

- -

-If the BLT extension to Tk is present, Pmw will use the BLT busy -command during modal dialogs to display a clock cursor. Also, the -Pmw.Blt interface to the BLT busy, graph, stripchart, tabset and -vector commands will be available. BLT versions 2.4i and greater are -supported (tested up to 2.4u). You can find BLT at -http://www.tcltk.com/blt/. - -

- -
-

Distribution and installation

-

-Releases of the Pmw distribution are available via http from -http://download.sourceforge.net/pmw/. This release is available -as -Pmw.1.2.tar.gz, released on 5 August 2003. -This is a compressed tar file. Under Linux, Unix, etc, you will need to -unpack it using tar and you may also need to use -gzip or gunzip to uncompress it. -Under Microsoft Windows, you will need a program such as WinZip (http://www.winzip.com) that can -unpack the gzipped tar files. You may need to change the suffix of -the file to .tgz for WinZip to recognise it. - -

- -

- -This will unpack into a directory named Pmw. You now need to put this -directory somewhere python can find it, preferably in one of the -standard places, such as in the site-packages directory -(eg: /usr/lib/python2.2/site-packages/Pmw) or the -sys.prefix directory (eg: C:\Program -Files\Python\Pmw or /usr/lib/python2.2). - -

- -

- -For example, under Unix, assuming you have placed the tar file in the -/tmp directory, you can simply run the following -commands: - -

- -
-
-
-cd /usr/lib/python2.2/site-packages
-gunzip /tmp/Pmw.1.2.tar.gz (or gzip -d /tmp/Pmw.1.2.tar.gz)
-tar xvf /tmp/Pmw.1.2.tar
-
-
-
- -

- -If you do not have write permission for these standard directories, -place the Pmw -directory somewhere on your PYTHONPATH or -sys.path. If this is not possible, place the Pmw -directory somewhere else and add the parent directory to your -PYTHONPATH or sys.path. - -

- -

- -If you have previously installed Pmw version 0.6 or later, then the -new version can share the same Pmw directory as the -previous versions. You will need to perform the tar -extraction in the directory containing (that is, the parent directory -of) the existing Pmw directory. By default, your -applications will use the most recent version of Pmw. If required, -the function Pmw.setversion() can be used to specify a -version to be used. See the reference manual for details. If you are -no longer using the older versions, you can safely remove the -corresponding subdirectories from the Pmw directory. - -

- -

- -If you need assistance in installing BLT under Unix, please contact me -(gregm@iname.com) and I -will try to help. For other operating systems, such as Microsoft or -Macintosh, you should try asking the python newsgroup. If anyone can -give me a description of how to install BLT under other operating -systems please contribute it and I will place it here. - -

- -
-

Documentation

-

-The doc directory for each Pmw version contains all the -documentation for that version of Pmw. See the local home page for a complete list of documents. The -files in this directory are also available from the official Pmw home page. - -

- -

-An excellent tutorial and reference covering the Pmw interface to the -powerful Blt graph widget, "A User's Guide to -Pmw.Blt" written by Bjørn Ove Thue and Hans Petter Langtangen, is -available. You can also download the full -HTML document for local viewing. - -

-
-

Demonstrations and tests

-

- A good way to get an overview of the functionality provided by Pmw - is to run the demonstrations and tests and look at the demonstration - code. To view a comprehensive demonstration of many of the features - of Pmw run the All.py script, which can be found in the - demos subdirectory of each version of Pmw. -

- -

- - You do not have to install Pmw to run the demonstrations and tests, - simply change into the appropriate directory and run the file - All.py. See Demonstrations and tests for more - information about running the demonstrations and tests and how to - create your own. -

- -

- -Note that there are some bugs in later versions of BLT (at least 2.4t -and 2.4u) which cause some tests of Pmw.Blt.Graph to crash with -python2.0 under Linux. These tests have been commented out (until BLT -is fixed). - - -

-

Contributions welcome

- -

-If you create some whiz-bang megawidgets and would like to contribute -them to Pmw, they will be most welcome. You should be able to get -some idea of the coding style used in Pmw code by reading How to build Pmw megawidgets and by looking -at the Pmw library code itself in the lib directory of -each Pmw version. - -

- -

-If you would like to contribute a megawidget, it would be preferable if it -also came with a simple demonstration and a test script. See Demonstrations and tests for information -about how to create new demonstrations and tests. -

- -

-Each megawidget should also have a reference manual describing its -options, components and methods. - -

- - -
-

Generating the documentation

- -

-The released reference manuals are -automatically generated by merging specially marked-up text with the -output from megawidget query methods, such as -components(), options() and -componentaliases(), and various other introspective -devices. If you are interested to see how the documentation is generated, -you can fetch the marked-up text and the python script to convert the -text to html from - -http://download.sourceforge.net/pmw/Pmw.1.2.docsrc.tar.gz -. Download this -file into the Pmw/Pmw_1_2 directory of the Pmw source -tree. Unzip and untar the file. This will create a -docsrc sub-directory of Pmw/Pmw_1_2. If -you want to keep the documentation which came with the Pmw -distribution, rename the old doc directory. Then change -directory to docsrc and run createmanuals.py. -After printing lots of warnings about documentation that has not been -written yet, this will create a new doc directory -containing all the html documentation. -

- -

-Here is an example set of commands to unpack the documentation source -and regenerate the documentation, assuming you have downloaded the -source in the Pmw/Pmw_1_2 directory: -

- -
-
-
-cd Pmw/Pmw_1_2
-gunzip Pmw.1.2.docsrc.tar.gz
-tar xvf Pmw.1.2.docsrc.tar
-mv doc doc.old
-cd docsrc
-./createmanuals.py
-
-
-
- -

-If running under Unix, you will need to run the -createmanuals.py script with a valid DISPLAY environment -variable, since it creates each megawidget and then queries it for its -options, components, etc. This is because Tk (and hence Tkinter) -requires a connection to an X server to run. - -

- -
-

Future plans and bugs

- -

-The todo list contains a long list of of -suggestions, bugs and enhancements for Pmw. If you are interested in -doing any of these, please let the maintainer -(gregm@iname.com) know. -Some of the items in the todo list may be considered bugs. There are -also some other problems due to idiosyncrasies in the implementation -of Tk. - -

- -
-

Licence

- -

-The official Pmw licence (see copyright) -basically lets you do anything with Pmw as long as you don't hurt anyone. -There is also another licence, the "Postcard Licence": -

- -"I'd like to get a postcard from you! I'm interested in who is using -Pmw, where you live and where in the world Pmw is doing it's job" - -

-Please send me an e-mail to -gregm@iname.com -to get my postal address. -

- -
-

Acknowledgements

- -

-The initial ideas for Pmw were blatantly stolen from the itcl -extensions -[incr Tk] -by Michael McLennan and -[incr Widgets] -by Mark Ulferts. Several of the megawidgets are direct translations -from the itcl to python. -

- -

-The base classes and most megawidgets were written by Greg McFarlane -and Peter Munnings. Contributed megawidgets include: Pmw.TimeCounter -by Joe VanAndel, Pmw.Group and an early version of Pmw.NoteBook by Case Roole, -Pmw.ScrolledCanvas, Pmw.ScrolledFrame and another early version of -Pmw.NoteBook by Joe Saltiel -and Pmw.OptionMenu by Roman Sulzhyk. A big thank you to the following -people for their bug reports, fixes, enhancements and suggestions: - -David Ascher, -Robin Becker, -Siggy Brentrup, -Mark Colclough, -Jerome Gay, -Clemens Hintze, -Rob Hooft -Jack Jansen, -Jonathan Kelly, -Magnus Kessler, -Matthias Klose, -Andreas Kostyrka, -Fredrik Lundh, -Magnus Lycka, -Graham Matthews, -Dieter Maurer, -Michael McLay, -Daniel Michelson, -Georg Mischler, -Rob Pearson, -Case Roole, -Joe Saltiel, -Roman Sulzhyk, -Shen Wang, -Chris Wright, - and -Guido van Rossum. - -Special thanks to Case Roole and Michael McLay for help with getting -Pmw to work with python packages and many other nifty features. - -My deepest apologies if I have forgotten anyone. Please let me know. - -

- -

-The Pmw home page and project site is made available courtesy of -SourceForge. - -

-

- -The current maintainer is Greg McFarlane. I monitor the Pmw -discussion and announcement mailing list so please send any -problems, comments, suggestions or enhancements to the list. You may -also contact me directly at gregm@iname.com. - -

-
-
- - -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home - -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/todo.html b/Pmw/Pmw_1_2/doc/todo.html deleted file mode 100644 index 9ca6889f..00000000 --- a/Pmw/Pmw_1_2/doc/todo.html +++ /dev/null @@ -1,1111 +0,0 @@ - - - - - - Pmw todo list - - - - -

Pmw todo list

- -

-This is a long list of suggestions and enhancements for Pmw. If -you are interested in doing any of these, please let the Pmw maintainer -(gregm@iname.com) know.

- -

New Pmw megawidgets

-
  • Multicolumn listbox.

    -

    Useful features - smooth scrolling, embedded images, different - fonts and colours, text correctly masked when it is longer than - its column width, interactive resizing of columns.

    - -

    Probably should be implemented as canvas widget rather than by - using multiple frames or multiple listboxes. There would be a - lot of work needed to position all the elements - you can't just - pack or grid them.

    - - -
  • -
  • File dialog.

    - -
  • -
  • Main window class (App class), with menu bar, information line - with status boxes and an about box. (See iwidgets' mainwindow - class for example.) This should handle creation of multiple main - windows, recycling of unused main windows and should exit if - last open main window is closed.

    - -
  • -
  • Searchable text megawidget.

    - -
  • -
  • Tree browser.

    - -
  • -
  • Check out Doug Hellmann's contributed megawidgets at - <http://www.mindspring.com/~doughellmann/Projects/PmwContribD> or - <http://members.home.net/doughellmann/PmwContribD/> - and integrate into Pmw.

    - -
- -

Changes to current megawidgets

-

MegaToplevel

-
  • Modify activate() geometry argument to allow window positioning - relative to the pointer, another window or the screen and - allow the centering of the window relative to the - positioning point or by a specified offset. Also add the - ability to position the window so that the mouse is over a - particular widget in the toplevel.

    -

    Should handle all combinations of

    -
     when (always/first)
    - where (center/geometry/mouse)
    - parent (screen/window)
    -
    - and None (don't position)
    - - -

    Check Tix4.1.0/library/DialogS.tcl center method for how to - center over another window

    - -

    Check iwidget's shell.itk for code to center widget over - screen or another widget.

    - -

    See Pmw.Balloon code for how to position over pointer.

    - -

    Tcl code to center over another (parent) window:

    -
     # center client relative to master (default xoff, yoff = -1)
    - set geomaster [split [wm geometry $master] "x+"]
    - set geoclient [split [wm geometry $client] "x+"]
    -
    - if {$xoff == -1} {
    -   set xoff [expr (
    -     ([lindex $geomaster 0] - [lindex $geoclient 0]) / 2)]
    - }
    - set newxpos [expr [lindex $geomaster 2] + $xoff]
    -
    - if {$yoff == -1} {
    -   set yoff [expr (
    -     ([lindex $geomaster 1] - [lindex $geoclient 1]) / 2)]
    - }
    - set newypos [expr [lindex $geomaster 3] + $yoff]
    -
    - wm geometry $client +$newxpos+$newypos
    - - -

    More tcl code to center dialog over another (parent) window:

    -
     (args: parent dlg)
    - # First, display the dialog offscreen to get dimensions.
    - set screenW [winfo screenwidth $parent]
    - set screenH [winfo screenheight $parent]
    - set w [expr $screenW + 1]
    - wm geometry $dlg +$w+0
    - update
    -
    - # Get relative center of parent. 
    - set w [winfo width $parent]
    - set h [winfo height $parent]
    - set w [expr $w/2]
    - set h [expr $h/2]
    -
    - # Get and add screen offset of parent.
    - set w [expr $w + [winfo rootx $parent]]
    - set h [expr $h + [winfo rooty $parent]]
    -
    - # Get dimensions of dialog.
    - set dlgW [winfo width $dlg]
    - set dlgH [winfo height $dlg]
    -
    - # Make adjustments for actual dimensions of dialog.
    - set w [expr $w - $dlgW / 2]
    - set h [expr $h - $dlgH / 2]
    -
    - # Let's keep the entire dialog onscreen at all times.
    - # Center in screen if things are awry.
    - set recenter 0
    - if { $w < 0 } { set recenter 1 }
    - if { $h < 0 } { set recenter 1 }
    - if { [expr $w + $dlgW] > $screenW } { set recenter 1 }
    - if { [expr $h + $dlgH] > $screenH } { set recenter 1 }
    - if { $recenter } {
    -   set w [expr ($screenW -$dlgW) / 2]
    -   set h [expr ($screenH - $dlgH) / 2]
    - }
    -
    - wm geometry $dlg +$w+$h
    - - - -
  • -
  • Add geometry argument to show() (same as activate() above).

    - -
- -

Dialog

-
  • Add label (header?) to Dialog class. May not be necessary, or - too complicated.

    - -
- -

ButtonBox

-
  • When a horizontal ButtonBox is stretched, the left button - stays anchored to the left edge and there is too much space - between the last button and the right edge.

    - -
  • -
  • Add an option to either evenly space the buttons across the - button box, or to keep them together and justify them to the - left, right or center. Check that deleting buttons works - correctly.

    - -
- -

ComboBox

-
  • Remove arrowrelief option from ComboBox and do what counter - does: gets value of arrow's relief just before sinking it, - then restores it later.

    - -
  • -
  • Change bindings: remove all bindings from arrow key and remove - arrow key from <tab> focus sequence; only implement these - bindings on the entry widget:

    -
     Up    popup dropdown list, scroll up if already displayed
    - Down  popup dropdown list, scroll down if already displayed
    - Esc   popdown dropdown list, return entry to previous value
    - Enter popdown dropdown list, execute current selection
    - -

    Remove bindings from listbox and scrollbar(s), so that all - bindings are via the entry widget?

    - - -
  • -
  • When entering keys when list is displayed, scroll list to - first entry beginning with entered keys. If no match, - scroll list to top.

    - -
  • -
  • Remove many of the arrow bindings from Pmw.ComboBox - there - are just too many key bindings on the arrow button. There - is no need for it to respond to keys such as the up/down - keys when the adjacent Entry widget already does so. I - propose to remove all Pmw.ComboBox arrow button key bindings - except for <space>, which can be used to bring up the - dropdown list. The Entry widget behaviour would remain - unchanged: when it has focus, you can use the up/down keys - to go to the next/previous entries and then use <Return> to - invoke the selection command.

    -

    Alternatively, make the bindings the same as the MS-Windows - combobox. (Use the url entry field in Navigator or IE as an - example of MS-Windows behaviour). These have been reported - to be:

    -
    • All mouse actions are exclusively triggered by the left - button.

      - -
    • -
    • Right button displays "Direkthilfe" on my german system - ("Direct Help"). This is a floating button, that - triggers display of a tool tip like the |?| button that - appears next to the |x| at the right end of the title - bar of some native windows dialogs.

      - -
    • -
    • The arrow is very slim (acutally flat: width/height is - about 2/1)

      - -
    • -
    • Entry and popup have the same color ("window color")

      - -
    • -
    • The popup has a 1 pixel dark border, no spacing between - popup and scrollbar.

      - -
    • -
    • If the box has the focus, the full entry is displayed in - "selected" style.

      - -
    • -
    • If the box has the focus, up and left keys rotate items - up, down and right keys rotate items down, all with - immediate effect.

      - -
    • -
    • If the box has the focus, keys a-z (not case sensitive) - rotate through the items with same first character, with - immediate effect.

      - -
    • -
    • No separate focus for the arrowbutton

      - -
    • -
    • Discussing how the combobox behaves with arrow keys when - it has the focus: "The concept is almost identical to - what you already have, just gives more visual feedback. - In your current implementation you allow to rotate - through the values with the up and down arrow keys, - showing the strings in the entryfield, and accepting the - values when the user presses the spacebar (hmmm, how can - I exit this without moving back to the original value - manually?). On Windows, the choice is not shown in the - entryfield, but the popup opens when you press the up or - down arrow keys, as if you clicked on the arrowbutton, - and you then navigate the values in the listbox. This - avoids the display of not finally selected values in the - entryfield and is a lot more obvious and less confusing. - The current behaviour certainly confused me, which is - why I first proposed the changes to the moveup/down - methods." (Georg Mischler)

      - -
    - -

    Also, check bindings on other megawidgets for consistency.

    - - -
  • -
  • Modify Pmw.ComboBox so that the width of the entry widget is - forced to be the same as the width of the dropdown listbox. - If the "width" option to the standard listbox is 0, Tk sets - the requested width of the listbox to be just large enough - to hold the widest element in the listbox. Using this - option, I can see that listbox.winfo_reqwidth() is changing - as I insert items into an unmapped listbox. The question - is, how do I get notified of these events so that I can set - the width of the entry?

    -

    The problem is that the listbox is in another toplevel which - has not yet been displayed, so I can't bind to <Configure> - to determine its width.

    - -

    One suggestion is to override the insert and delete methods - of the Listbox class. The problem with this is what if the - font changed, or the borderwidth, etc? You would need to - override and check many more methods.

    - - -
  • -
  • Add ability to tearoff dropdown list (suggested by Dean N. - Williams).

    - -
  • -
  • Should be able to disable/enable arrow button.

    - -
- -

Counter

-
  • Add option for different increment/decrement behaviour. For - example, assuming increment is 1:

    -
    1. Current behaviour - move to the next multiple of the - increment, eg: 1.0 -> 2.0, 1.234 -> 2.0

      - -
    2. -
    3. Add or subtract the increment to whatever is displayed, - eg: 1.0 -> 2.0, 1.234 -> 2.234

      - -
    4. -
    5. Move to the next multiple of the increment, offset by some value. - eg: (if offset is 0.5) 0.5 -> 1.5, 1.234 -> 1.5, 1.678 -> 2.5

      - -
    - -
  • -
  • Add wrap option (to wrap around at limits) (then don't need - time24 arg to 'time' datatype).

    - -
  • -
  • Add a state option to disable Counter.

    - -
  • -
  • Add option to Counter to allow the buttons to be on the same - side, one on top of the other, like Tix, Itcl, Motif, - Windows 95, etc. There should probably also be an option to - lay the current large buttons on the same side of the entry - field, next to each other.

    - -
  • -
  • Redo TimeCounter using vertical Counter, add limitcommand - option to Counter to allow overflow from seconds to minutes - to hours

    - -
- -

Arrowed megawidgets (Counter, ComboBox, TimeCounter)

-
  • Potential construction speed up if Canvas arrows are replaced - by Label with Bitmap or BitmapImage. The hard part would be - to make the bitmap change size depending on size of Label.

    - -
  • -
  • Pmw.drawarrow should draw arrows which look like Tk cascade - menu arrows.

    - -
- -

EntryField

-
  • Can it be modified to change all entered characters to upper - or lower case automatically? Or first-upper or - first-of-each-word-upper?

    - -
  • -
  • If the validity of the currently displayed text is ERROR, - allow any changes, even those which result in invalid text. - This is useful when invalid data has been given to the - value option and the user is trying to correct it.

    - -
- -

LabeledWidget

-
  • Add tix-style border.

    - -
- -

MenuBar

-
  • Maybe Pmw.MenuBar should also have (optional) balloon help - for menu items as well as menu buttons. I am not sure - whether users would find this useful.

    - -
  • -
  • The status help hints do not appear when using F10/arrow - keys.

    - -
  • -
  • Look at the Tk8.0 menu demo and check the help bindings for - ideas, in particular, how can you get help when using - keyboard bindings.

    - -
  • -
  • Check the new menu features in Tk8.0 for creating "native" - menu bars and the special ".help" menu.

    - -
  • -
  • Add index() method.

    - -
  • -
  • Add a 'position' option to addmenu and deletemenu methods. - This option should accept an index number, a menuName or - Pmw.END.

    - -
  • -
  • Look at itcl menubar for ideas.

    - -
- -

Balloon

-
  • Positioning of the balloon with respect to the target - widget or canvas item: There are a number of ways that - Pmw.Balloon could be improved. For example, currently the - the top left corner of the balloon is positioned relative to - the bottom left corner of the target, offset by the - [xy]offset options. These options apply to all targets - - they can not be set differently for different targets.

    -

    To make it more configurable, the user should be able to - specify, for each target:

    -
    • the base position in the target relative to which the - balloon should be placed (n, s, e, w, nw, sw, ne, se, c) - (Currently sw)

      - -
    • -
    • the x and y offsets (Default (20, 1))

      - -
    • -
    • the position in the balloon that should be placed at the - offset position (n, s, e, w, nw, sw, ne, se, c) - (Currently nw)

      -

      Note, if this is anything other than nw, - update_idletasks() will need to be called to get the - size of the balloon before it is positioned - there is a - possibility that this may cause weird ugly flashing.

      - - -
    • -
    • whether either the base x or y position should be taken - relative to the current mouse position rather than as - one of the corners of the target. This would be useful - for large targets, such as text widgets, or strange - shaped canvas items. This could be specified using - special base positions, such as (nm, sm, em, wm). For - example, for 'sm', the x base position is the mouse x - position and y base position is the bottom (south) edge - of the target.

      - -
    - -

    The user should be able to specify global defaults for all - of these, as well as be able to override them for each - target. The Pmw.Balloon options and their defaults could - be:

    -
     basepoint   sw        # Position on target.
    - anchor      nw        # Position on the balloon
    - xoffset     20        # x distance between basepoint and anchor
    - yoffset     1         # y distance between basepoint and anchor
    - - -

    To be able to override these, the bind() and tagbind() - methods would have to accept these as additional arguments. - Each would default to None, in which case the default values - at the time the balloon is deiconified would be used.

    - -

    I'm not sure about how to handle the case when the balloon - is configured to come up under the mouse. When this happens - the balloon flashes on and off continuously. This can - happen now if you set the yoffset to a negative number. - Should the balloon widget detect this and do something about - it?

    - - -
  • -
  • Add showballoon(x, y, text) method to Balloon and use in - balloon help for a listbox:

    -

    On 3 Dec, Michael Lackhoff wrote:

    - -
     And another question:
    - Is it possible to create a balloon-help for the entries
    - in the listbox?  Not all the information is in the
    - listbox and it would be nice if a balloon help could
    - give addtional information.
    - -

    Rather than popup a balloon help window as the mouse moves - over items in the listbox, I think it would be better if it - pops up after you clicked on an item (or a short time - afterwards). Pmw.Balloon displays the balloon help a short - time after the mouse enters a widget, so is not directly - usable in this case. However, a method could be added to - Pmw.Balloon to request it to popup the balloon at a - particular x,y position. This method could be called from - the listbox_focus method above. Something like:

    -
     def listbox_focus(self, event):
    -     self.indexlist.component('listbox').focus_set()
    - -
         text = self.indexlist.getcurselection()
    -     # expand text to whatever you want:
    -     text = 'This is ' + text
    -     self.balloon.showballoon(x, y, text)
    - - -

    The Pmw.Balloon showballoon() method would have to set a - timer which sometime later calls another method which - displays the text. You would also need to bind - <ButtonRelease-1> to a hideballoon() method which withdraws - the popup.

    - - -
  • -
  • The balloon can be displayed off-screen if the window is - near the edge of the screen. Add a fix so that the balloon - always stays on the screen (but does not popup under the - mouse, otherwise it will immediately pop down).

    - -
  • -
  • Add a fix so that the balloon does not disappear if the - mouse enters it. Could do this by setting a short timer on - the Leave event before withdrawing the balloon and if there - is an Enter event on the balloon itself, do not withdraw it.

    - -
  • -
  • For tagged items in text widgets, the balloon is placed - relative to the character in the tagged item closest to the - mouse. This is not consistent: in the other cases - (including canvas), the balloon is placed relative to the - bottom left corner of the widget or canvas item. This - should also be the case for text items.

    - -
  • -
  • Is the new (in Tk8) "<<MenuSelect>>" event useful for - balloon and/or status help.

    - -
- -

MessageBar

-
  • Finish logmessage functionality.

    - -
  • -
  • Add colours and fonts to MessageBar message types. For - example, systemerror message types could have bold font on a - red background.

    - -
  • -
  • Add message logging history view (like the ddd debugger).

    - -
- -

NoteBook

-
  • Notebook should recalculate layout if the requested size of a tab - changes (eg font size, text, etc).

    - -
  • -
  • The tabpos option should accept s, e and w as well as n.

    - -
  • -
  • Possible new options (borrowed from iwidgets):

    -
    • equaltabs

      -

      If set to true, causes horizontal tabs to be equal in - in width and vertical tabs to equal in height.

      - -

      Specifies whether to force tabs to be equal sized or - not. A value of true means constrain tabs to be equal - sized. A value of false allows each tab to size based - on the text label size. The value may have any of the - forms accepted by the Tcl_GetBoolean, such as true, - false, 0, 1, yes, or no.

      - -

      For horizontally positioned tabs (tabpos is either s or - n), true forces all tabs to be equal width (the width - being equal to the longest label plus any padX speci- - fied). Horizontal tabs are always equal in height.

      - -

      For vertically positioned tabs (tabpos is either w or - e), true forces all tabs to be equal height (the height - being equal to the height of the label with the largest - font). Vertically oriented tabs are always equal in - width.

      - -

      Could have a special value which sets equal sized and - also forces tabs to completely fill notebook width - (apparently like - Windows).

      - - -
    • -
    • tabgap

      -

      Specifies the amount of pixel space to place between - each tab. Value may be any pixel offset value. In addi- - tion, a special keyword overlap can be used as the - value to achieve a standard overlap of tabs. This value - may have any of the forms acceptable to Tk_GetPixels.

      - - -
    • -
    • raiseselect

      -

      Sets whether to raise selected tabs slightly (2 pixels).

      - -

      Specifes whether to slightly raise the selected tab - from the rest of the tabs. The selected tab is drawn 2 - pixels closer to the outside of the tabnotebook than - the unselected tabs. A value of true says to raise - selected tabs, a value of false turns this feature off. - The default is false. The value may have any of the - forms accepted by the Tcl_GetBoolean, such as true, - false, 0, 1, yes, or no.

      - - -
    • -
    • bevelamount

      -

      Specifies pixel size of tab corners. 0 means no corners.

      - - -
    - -
  • -
  • There should be a way to temporarily hide a page, without - deleting it (like pack_forget). (Suggested by Michel Sanner)

    - -
- -

OptionMenu

-
  • Should accept focus and obey up and down arrow keys.

    - -
- -

PanedWidget

-
  • Add index() method

    - -
  • -
  • Modify all methods so that they accept Pmw.END as a pane - identifier as well as an index or a name.

    - -
  • -
  • Check iwidgets pane and panedwindow classes.

    - -
- -

RadioSelect

-
  • Add insert() and delete() methods.

    - -
  • -
  • The index method should have forInsert argument.

    - -
  • -
  • Add Pmw.SELECT to index() method. For single selectmode - this returns an integer, for multiple selectmode this - returns a list of integers.

    - -
  • -
  • Add option to set background color on selected buttons. - Maybe should also be able set selected foreground as well. - Any others?

    - -
- -

LogicalFont

-
  • Add boldFixed fonts,

    - -
  • -
  • Search for closest size font if no exact match.

    - -
  • -
  • Maybe replace with Tk8.0 font mechanism.

    - -
  • -
  • Can the Tk8.0 font measuring functionality be used in Pmw somehow?

    - -
- -

Scrolled widgets

-
  • Can some common scrolling methods be factored out, either as - a base class, "ScrolledMixin" mixin class or as helper functions? - Candidate methods: constructor, destroy, interior, _hscrollMode, - _vscrollMode, _configureScrollCommands, _scrollXNow, _scrollYNow, - _scrollBothLater, _scrollBothNow, _toggleHorizScrollbar, - _toggleVertScrollbar.

    - -
  • -
  • ScrolledField should have optional arrow buttons, so that it - can still be scrolled even if the mouse does not have a - middle button.

    - -
- -

Miscellaneous

-
  • Add a button to the Pmw "Stack trace window" which - optionally removes all grabs:

    -

    I normally interact with the "Stack trace window" - immediately, and dismiss it afterwards. In many cases - where a bug appears like this, the rest of the application - is still functional (many of the problems appearing at - this stage of development of my application are unforeseen - exceptions communicating with a robot on the other end of - a socket, not affecting the GUI per se). For that reason - I'd prefer if the "stack trace window" would push another - grab on the grab stack (if any grabs are active at the - moment the exception occurs). Could the window have an - extra "Terminate application" option for this case?

    - - -
  • -
  • need to handle component option queries in configure():

    -
     foo = Pmw.AboutDialog(applicationname = 'abc XYZ')
    - foo.component('message').configure('text')    - works
    - foo.cget('message_text')                      - works
    - foo.configure('message_text')                 - doesn't
    - - -
  • -
  • Implement bindings (ComboBox, etc) via a dictionary lookup, - to allow people to invent new bindings, such as for - handicapped users. (Suggested by Michael McLay)

    - -
  • -
  • Modify bundlepmw.py so that it checks Pmw.def to see that no - files have been missed.

    - -
  • -
  • Potential cheap speedup by adding this to each module, or - inside functions if it has a loop containing calls to - builtins:

    -
     from __builtin__ import *
    - - -
  • -
  • Look at how update_idletasks and after_* are used in Pmw - - are they consistent? could it be improved? What are the - problems of using these on other bits of an application - (such as when the size of the toplevel is being determined - for the window manager).

    - -
  • -
  • If lots of errors occur (such as in a fast time callback) - the error window may not appear, since Tk will wait until it - is idle - which may never occur. The solution is to call - update_idletask when updating the error window, but only - after a short time has passed. This will provide better - user response. However, it may not be possible to do this - if some python interpretes (omppython, for example) do not - handle calls to update_idletasks at certain times.

    - -
  • -
  • In the Pmw FAQ, in the "Why don't Pmw megawidgets have a - 'state' option?" section, it mentions several Pmw - megawidgets that can not be disabled. Fix them.

    - -
  • -
  • Add RCSID version string to all files.

    - -
  • -
  • When raising exceptions use the third argument to raise:

    -
     raise SimulationException, msg, sys.exc_info()[2]
    - - -
  • -
  • When update_idletasks is called all pending changes are - flushed to the window system server. However, it may take - some time for the server to display the changes. If it is - required that the display be up-to-date, update_idletasks - should be followed by a call that blocks until processed by - the server and a reply received. This may be useful in - Pmw.busycallback to ensure the busy cursor remains visible - until the display is actually modified.

    - -
  • -
  • There is a small bug which appears only with Tk8.0 (the bug - is not apparent with Tk4.2). If a dialog is activated and - pops up directly over the cursor and the dialog has a - default button, then pressing the <strong>Return</strong> - key will not invoke the default button. If you move the - mouse out of and then back into the dialog, pressing the - <strong>Return</strong> key will work. This behaviour has - been noticed in Tcl-only programs, so it is probably a bug - in Tk. (Tested on Solaris.)

    - -
  • -
  • Modify PmwBlt.py to use blt2.4 instead of blt8.0.unoff. - Nick Belshaw <nickb@earth.ox.ac.uk> is looking at wrapping - the new BLT StripChart and TabSet into Pmw.

    - -
  • -
  • Perhaps Pmw should have its own exception defined, like - TkInters's TclError, perhaps called PmwError.

    - -
  • -
  • This one is caused by a bug in the implementation of Tcl/Tk - for Microsoft Windows NT (and maybe other Microsoft - products). Mouse release events can get lost if the - grab_set and grab_release commands are used and the mouse - goes outside of the window while the mouse button is down. - This can occur while Pmw modal dialogs are active. Below - is some Tkinter-only code which demonstrates the problem. - Maybe there is a work around.

    -
     # Test script to demonstrate bug in Tk
    - #implementation of grab under NT.
    -                                 
    - # Click on "Dialog" to bring up the modal
    - # dialog window.  Then button down on the scale,
    - # move the mouse outside the window,
    - # then button up.  The scale slider will still
    - # be sunken and clicks on the "OK" button
    - # will be ineffective.
    - 
    - import Tkinter
    - 
    - def activate():
    -     waitVar.set(0)
    -     toplevel.deiconify()
    -     toplevel.wait_visibility()
    -     toplevel.grab_set()        # Problem here
    -     toplevel.focus_set()
    -     toplevel.wait_variable(waitVar)
    - 
    - def deactivate():
    -     toplevel.withdraw()
    -     toplevel.grab_release()    # and here
    -     waitVar.set(1)
    - 
    - root = Tkinter.Tk()
    - toplevel = Tkinter.Toplevel()
    - waitVar = Tkinter.IntVar()
    - toplevel.withdraw()
    - scale = Tkinter.Scale(toplevel, orient='horizontal', length=200)
    - scale.pack()
    - button = Tkinter.Button(toplevel, text='OK', command=deactivate)
    - button.pack()
    - 
    - button = Tkinter.Button(text='Dialog', command=activate)
    - button.pack()
    - button = Tkinter.Button(text='Exit', command=root.destroy)
    - button.pack()
    - 
    - root.mainloop()
    - - -
- - -

Documentation

-
  • Document how to get Pmw working on a Mac, for example:

    -
    • Unzip and untar

      -

      This depends on what you use to unpack the tar file. If - you use (macgzip and) SunTar you have to tell it that files - with ".py" extensions are text files (in the - preferences/file type section). If you use stuffit - expander: this can be made to do the conversion - correctly, but it could be that this only works if you set - the .py extension correctly in Internet Config.

      - -
      • Where do you untar Pmw?

        - -
      • -
      • How do you get line terminators correct (carriage - return/line feed)?

        - -
      • -
      • Is there any problem with file name case? (mixed - upper/lower case)

        - -
      • -
      • Is there any problem with file name length?

        - -
      -

      (Joseph Saltiel says: It was the same type of operation - as in Windows/Unix. Run a program that unzips it and - untars it. It seems to get case and length right on its - own.)

      - - -
    • -
    • Let python know where Pmw is

      -
      • If Pmw is in its own folder you will have to add the - parent of that folder to the sys paths in Edit - PythonPaths. If it is in the Python home folder, you - do not need to do this.

        - -
      • -
      • Make sure that the Pmw folder is called "Pmw" and not - something else. Since Pmw is a package, python expects - to find a "Pmw" folder somewhere in sys.path.

        - -
      -

      (Joseph Saltiel says: With the Python distribution on the - Mac there is an application called editPythonPrefs, when - you run it it gives you a list of a paths. These paths - are similiar to the PYTHONPATH variable. I just added the - path to Pmw at the bottom of this list.)

      - - -
    - -
  • -
  • Document general ideas about building guis, eg:

    -

    When I write gui applications, I usually defer creation of windows - as much as possible - this means that the application starts up - quickly because it usually only has to create the main window. - Whenever another window is required for the first time, it is - created then. When the user has finished with the window, the - window is withdrawn, not deleted, so that next time it is required - it much faster to come up.

    - -

    In summary - don't create a window until you need and - don't destroy a window if you may want it again.

    - -

    The amount of memory required to keep the windows should not be - very much - except for very long running programs where the user - may create thousands of different windows.

    - - -
  • -
  • Add class hierarchy diagram to documentation:

    -
     MegaArchetype
    -     MegaToplevel
    -        etc
    -     MegaWidget
    -        etc
    - - -
  • -
  • Add to doco something like: "Another way to extend a Pmw - megawidget is to specify a non-default type for one of the - components. For example text_pytype = FontText."

    - -
  • -
  • Document pyclass and pyclass = None (options for null components - are ignored; the only time this can be used is with the - Group's tag component - all - other's use the component widget in some way)

    - -
  • -
  • Create index of all Pmw methods, functions, options, components.

    - -
  • -
  • Add description of how to run the Pmw demos without installing.

    - -
  • -
  • Add description of how to install Pmw.

    - -
  • -
  • Describe grid structure of megawidgets, so that it is possible - to extend megawidgets by adding new widgets into the interior - (hence avoiding a childsite in most megawidgets)

    - -
  • -
  • Document error display and difference between callback and - binding error reports.

    - -
  • -
  • Document difference between 'Helvetica 12' and 'Helvetica size: 12' - in logicalfont.

    - -
  • -
  • Add to howtouse, to describe using the option database to set - options for a specific megawidget:

    -
     import Pmw
    - root = Pmw.initialise(useTkOptionDb = 1)
    - root.option_add('*entryfield24*Label.text', 'German')
    - e = Pmw.EntryField(hull_name = 'entryfield24', labelpos = 'w')
    - e.pack()
    - root.update()
    - - -
  • -
  • Also document hull_name and hull_class.

    - -
  • -
  • Finish FAQ, ReleaseProcedure and StructuredText test.

    - -
  • -
  • Put html through gifwizard and html lint.

    -
     http://www.cen.uiuc.edu/cgi-bin/weblint
    - (eg: http://www.cre.canon.co.uk/~neilb/weblint/manpage.html)
    - - -
  • -
  • Delete comments from source if they have been added to docs - (should not have two copies of anything).

    - -
  • -
  • Need to document non-standard initial values for component - options, such as border in ButtonBox and Dialog's childsite.

    - -
  • -
  • Docs should have DEFAULT BINDINGS section (like iwidget combobox).

    - -
  • -
  • Promote home page:

    -
     http://www.geocities.com/homestead/promote.html
    - http://www.submit-it.com/subopt.htm, etc
    - - -
  • -
  • Create man pages as well as html (modify createmanuals to produce both).

    - -
  • -
  • Maybe something with html frames like: itcl2.2/html/index.html

    - -
  • -
  • Add to starting.html a note that Pmw is a python "package" and add - a pointer to python documentation on packages.

    - -
  • -
  • Document scrolled widget implementations, explaining why they - are all slightly different (because the underlying widgets which - are being scrolled have different behaviors).

    - -
  • -
  • Make copyright clearer. Maybe borrow python's?

    - -
- -

Demos

-
  • Check for missing demos.

    - -
  • -
  • In all demos can move the three lines beginning with "Import Pmw - from the sibling directory", to inside "if __name__" clause. - Also, "sibling directory" is now incorrect. Also, add note that - this is only necessary when running demos without installing Pmw.

    - -
  • -
  • Change demo/All.py so that it displays the traceback if it - cannot load or run a demo (easier for users to report errors).

    - -
  • -
  • Add option to demo/All.py: "Display demos in separate window" - to allow resizing of sub-demos

    - -
  • -
  • TimeCounter and Spectrum demos beep when they come up, using:

    -
     root.option_add('*EntryField*value', 'VALUE')
    - - -
  • -
  • In demos, add title = 'blah' to top of file and replace - root.title(..) with root.title(title) at bottom.

    - -
  • -
  • Add comprehensive speed test demo which creates one or more of - each (common) megawidget. Remove old SpeedTest demo.

    - -
  • -
  • Check demos work when called from ptui. (Changes have to do - with calling compile/exec where __name__ is not the name of the - All.py script, but is '__builtin__')

    - -
  • -
  • PromptDialog demo should not remember password.

    - -
  • -
  • Finish Counter, Radioselect demos.

    - -
  • -
  • Modify the All demo so that you can reload a demo module.

    - -
  • -
  • The syntax-coloured code viewer looks strange on Microsoft NT, - because the size of the fonts differ. Check out Guido's - idle-0.1 text colouring for Pmw code viewer.

    - -
  • -
  • Document restrictions on adding bindings to a megawidget: you - probably need to bind to components of the megawidget and also - check that you are not destroying bindings set up by the - megawidget itself.

    - -
  • -
  • Add a demo that demonstrates setting the color scheme at run time.

    - -
- -

Tests

-
  • Check for missing tests, such as TimeCounter, RadioSelect, - SelectionDialog, MessageBar, MenuBar, ComboBoxDialog, Balloon.

    - -
  • -
  • Create test for useTkOptionDb option to Pmw.initialise().

    - -
  • -
  • Check that destroyed widgets' python classes are garbage - collected (add test and/or demo).

    - -
  • -
  • Add tests for changecolor, setscheme, etc.

    - -
  • -
  • Need Resources test.

    - -
  • -
  • Create tests for deriving from Pmw classes (eg ComboBox).

    - -
- -

Ideas

-
  • Add more Tix (www.xpi.com/tix/screenshot.html) and iwidgets widgets.

    - -
  • -
  • Look at spinner.itk for how to do vertical orientation on - same side for Counter.

    - -
  • -
  • Investigate these new features in Tk8.0 and see if they could be - used in Pmw:

    -
     embedded images in text widgets
    - destroy command ignores windows that don't exist
    -
    - - -
- - - -

- -

- - - -

- Pmw 1.2 - - 5 Aug 2003 - - Home - -

-
- - - - diff --git a/Pmw/Pmw_1_2/doc/transdove.gif b/Pmw/Pmw_1_2/doc/transdove.gif deleted file mode 100644 index a9d83cdc..00000000 Binary files a/Pmw/Pmw_1_2/doc/transdove.gif and /dev/null differ diff --git a/Pmw/Pmw_1_2/lib/Pmw.def b/Pmw/Pmw_1_2/lib/Pmw.def deleted file mode 100644 index 5965c118..00000000 --- a/Pmw/Pmw_1_2/lib/Pmw.def +++ /dev/null @@ -1,58 +0,0 @@ -# [Emacs: -*- python -*-] -# --- This is the Pmw definition file --- -# -# It is invoked by the Pmw dynamic loader in Pmw.__init__. -# -# widgets : tuple with the names of those widget classes that are -# stacked in a module of the same name. -# widgetclasses : dictionary from names of widget classes to module names. -# functions : dictionary from function names to modules names. -# modules : tuple of module names that don't contain widget classes -# of the same name. -# - -# Widgets whose name is the same as its module. -_widgets = ( - 'AboutDialog', 'Balloon', 'ButtonBox', 'ComboBox', - 'ComboBoxDialog', 'Counter', 'CounterDialog', 'Dialog', - 'EntryField', 'Group', 'HistoryText', 'LabeledWidget', - 'MainMenuBar', 'MenuBar', 'MessageBar', - 'MessageDialog', 'NoteBook', 'OptionMenu', 'PanedWidget', - 'PromptDialog', 'RadioSelect', 'ScrolledCanvas', 'ScrolledField', - 'ScrolledFrame', 'ScrolledListBox', 'ScrolledText', 'SelectionDialog', - 'TextDialog', 'TimeCounter', -) - -# Widgets whose name is not the same as its module. -_extraWidgets = { -} - -_functions = { - 'logicalfont' : 'LogicalFont', - 'logicalfontnames' : 'LogicalFont', - 'aboutversion' : 'AboutDialog', - 'aboutcopyright' : 'AboutDialog', - 'aboutcontact' : 'AboutDialog', - 'datestringtojdn' : 'TimeFuncs', - 'timestringtoseconds' : 'TimeFuncs', - 'setyearpivot' : 'TimeFuncs', - 'ymdtojdn' : 'TimeFuncs', - 'jdntoymd' : 'TimeFuncs', - 'stringtoreal' : 'TimeFuncs', - 'aligngrouptags' : 'Group', - 'OK' : 'EntryField', - 'ERROR' : 'EntryField', - 'PARTIAL' : 'EntryField', - 'numericvalidator' : 'EntryField', - 'integervalidator' : 'EntryField', - 'hexadecimalvalidator' : 'EntryField', - 'realvalidator' : 'EntryField', - 'alphabeticvalidator' : 'EntryField', - 'alphanumericvalidator' : 'EntryField', - 'timevalidator' : 'EntryField', - 'datevalidator' : 'EntryField', -} - -_modules = ( - 'Color', 'Blt', -) diff --git a/Pmw/Pmw_1_2/lib/PmwAboutDialog.py b/Pmw/Pmw_1_2/lib/PmwAboutDialog.py deleted file mode 100644 index fe78d276..00000000 --- a/Pmw/Pmw_1_2/lib/PmwAboutDialog.py +++ /dev/null @@ -1,52 +0,0 @@ -import Pmw - -class AboutDialog(Pmw.MessageDialog): - # Window to display version and contact information. - - # Class members containing resettable 'default' values: - _version = '' - _copyright = '' - _contact = '' - - def __init__(self, parent = None, **kw): - - # Define the megawidget options. - INITOPT = Pmw.INITOPT - optiondefs = ( - ('applicationname', '', INITOPT), - ('iconpos', 'w', None), - ('icon_bitmap', 'info', None), - ('buttons', ('Close',), None), - ('defaultbutton', 0, None), - ) - self.defineoptions(kw, optiondefs) - - # Initialise the base class (after defining the options). - Pmw.MessageDialog.__init__(self, parent) - - applicationname = self['applicationname'] - if not kw.has_key('title'): - self.configure(title = 'About ' + applicationname) - - if not kw.has_key('message_text'): - text = applicationname + '\n\n' - if AboutDialog._version != '': - text = text + 'Version ' + AboutDialog._version + '\n' - if AboutDialog._copyright != '': - text = text + AboutDialog._copyright + '\n\n' - if AboutDialog._contact != '': - text = text + AboutDialog._contact - - self.configure(message_text=text) - - # Check keywords and initialise options. - self.initialiseoptions() - -def aboutversion(value): - AboutDialog._version = value - -def aboutcopyright(value): - AboutDialog._copyright = value - -def aboutcontact(value): - AboutDialog._contact = value diff --git a/Pmw/Pmw_1_2/lib/PmwBalloon.py b/Pmw/Pmw_1_2/lib/PmwBalloon.py deleted file mode 100644 index e1f88683..00000000 --- a/Pmw/Pmw_1_2/lib/PmwBalloon.py +++ /dev/null @@ -1,365 +0,0 @@ -import os -import string -import Tkinter -import Pmw - -class Balloon(Pmw.MegaToplevel): - def __init__(self, parent = None, **kw): - - # Define the megawidget options. - optiondefs = ( - ('initwait', 500, None), # milliseconds - ('label_background', 'lightyellow', None), - ('label_foreground', 'black', None), - ('label_justify', 'left', None), - ('master', 'parent', None), - ('relmouse', 'none', self._relmouse), - ('state', 'both', self._state), - ('statuscommand', None, None), - ('xoffset', 20, None), # pixels - ('yoffset', 1, None), # pixels - ('hull_highlightthickness', 1, None), - ('hull_highlightbackground', 'black', None), - ) - self.defineoptions(kw, optiondefs) - - # Initialise the base class (after defining the options). - Pmw.MegaToplevel.__init__(self, parent) - - self.withdraw() - self.overrideredirect(1) - - # Create the components. - interior = self.interior() - self._label = self.createcomponent('label', - (), None, - Tkinter.Label, (interior,)) - self._label.pack() - - # The default hull configuration options give a black border - # around the balloon, but avoids a black 'flash' when the - # balloon is deiconified, before the text appears. - if not kw.has_key('hull_background'): - self.configure(hull_background = \ - str(self._label.cget('background'))) - - # Initialise instance variables. - self._timer = None - - # The widget or item that is currently triggering the balloon. - # It is None if the balloon is not being displayed. It is a - # one-tuple if the balloon is being displayed in response to a - # widget binding (value is the widget). It is a two-tuple if - # the balloon is being displayed in response to a canvas or - # text item binding (value is the widget and the item). - self._currentTrigger = None - - # Check keywords and initialise options. - self.initialiseoptions() - - def destroy(self): - if self._timer is not None: - self.after_cancel(self._timer) - self._timer = None - Pmw.MegaToplevel.destroy(self) - - def bind(self, widget, balloonHelp, statusHelp = None): - - # If a previous bind for this widget exists, remove it. - self.unbind(widget) - - if balloonHelp is None and statusHelp is None: - return - - if statusHelp is None: - statusHelp = balloonHelp - enterId = widget.bind('', - lambda event, self = self, w = widget, - sHelp = statusHelp, bHelp = balloonHelp: - self._enter(event, w, sHelp, bHelp, 0)) - - # Set Motion binding so that if the pointer remains at rest - # within the widget until the status line removes the help and - # then the pointer moves again, then redisplay the help in the - # status line. - # Note: The Motion binding only works for basic widgets, and - # the hull of megawidgets but not for other megawidget components. - motionId = widget.bind('', - lambda event = None, self = self, statusHelp = statusHelp: - self.showstatus(statusHelp)) - - leaveId = widget.bind('', self._leave) - buttonId = widget.bind('', self._buttonpress) - - # Set Destroy binding so that the balloon can be withdrawn and - # the timer can be cancelled if the widget is destroyed. - destroyId = widget.bind('', self._destroy) - - # Use the None item in the widget's private Pmw dictionary to - # store the widget's bind callbacks, for later clean up. - if not hasattr(widget, '_Pmw_BalloonBindIds'): - widget._Pmw_BalloonBindIds = {} - widget._Pmw_BalloonBindIds[None] = \ - (enterId, motionId, leaveId, buttonId, destroyId) - - def unbind(self, widget): - if hasattr(widget, '_Pmw_BalloonBindIds'): - if widget._Pmw_BalloonBindIds.has_key(None): - (enterId, motionId, leaveId, buttonId, destroyId) = \ - widget._Pmw_BalloonBindIds[None] - # Need to pass in old bindings, so that Tkinter can - # delete the commands. Otherwise, memory is leaked. - widget.unbind('', enterId) - widget.unbind('', motionId) - widget.unbind('', leaveId) - widget.unbind('', buttonId) - widget.unbind('', destroyId) - del widget._Pmw_BalloonBindIds[None] - - if self._currentTrigger is not None and len(self._currentTrigger) == 1: - # The balloon is currently being displayed and the current - # trigger is a widget. - triggerWidget = self._currentTrigger[0] - if triggerWidget == widget: - if self._timer is not None: - self.after_cancel(self._timer) - self._timer = None - self.withdraw() - self.clearstatus() - self._currentTrigger = None - - def tagbind(self, widget, tagOrItem, balloonHelp, statusHelp = None): - - # If a previous bind for this widget's tagOrItem exists, remove it. - self.tagunbind(widget, tagOrItem) - - if balloonHelp is None and statusHelp is None: - return - - if statusHelp is None: - statusHelp = balloonHelp - enterId = widget.tag_bind(tagOrItem, '', - lambda event, self = self, w = widget, - sHelp = statusHelp, bHelp = balloonHelp: - self._enter(event, w, sHelp, bHelp, 1)) - motionId = widget.tag_bind(tagOrItem, '', - lambda event = None, self = self, statusHelp = statusHelp: - self.showstatus(statusHelp)) - leaveId = widget.tag_bind(tagOrItem, '', self._leave) - buttonId = widget.tag_bind(tagOrItem, '', self._buttonpress) - - # Use the tagOrItem item in the widget's private Pmw dictionary to - # store the tagOrItem's bind callbacks, for later clean up. - if not hasattr(widget, '_Pmw_BalloonBindIds'): - widget._Pmw_BalloonBindIds = {} - widget._Pmw_BalloonBindIds[tagOrItem] = \ - (enterId, motionId, leaveId, buttonId) - - def tagunbind(self, widget, tagOrItem): - if hasattr(widget, '_Pmw_BalloonBindIds'): - if widget._Pmw_BalloonBindIds.has_key(tagOrItem): - (enterId, motionId, leaveId, buttonId) = \ - widget._Pmw_BalloonBindIds[tagOrItem] - widget.tag_unbind(tagOrItem, '', enterId) - widget.tag_unbind(tagOrItem, '', motionId) - widget.tag_unbind(tagOrItem, '', leaveId) - widget.tag_unbind(tagOrItem, '', buttonId) - del widget._Pmw_BalloonBindIds[tagOrItem] - - if self._currentTrigger is None: - # The balloon is not currently being displayed. - return - - if len(self._currentTrigger) == 1: - # The current trigger is a widget. - return - - if len(self._currentTrigger) == 2: - # The current trigger is a canvas item. - (triggerWidget, triggerItem) = self._currentTrigger - if triggerWidget == widget and triggerItem == tagOrItem: - if self._timer is not None: - self.after_cancel(self._timer) - self._timer = None - self.withdraw() - self.clearstatus() - self._currentTrigger = None - else: # The current trigger is a text item. - (triggerWidget, x, y) = self._currentTrigger - if triggerWidget == widget: - currentPos = widget.index('@%d,%d' % (x, y)) - currentTags = widget.tag_names(currentPos) - if tagOrItem in currentTags: - if self._timer is not None: - self.after_cancel(self._timer) - self._timer = None - self.withdraw() - self.clearstatus() - self._currentTrigger = None - - def showstatus(self, statusHelp): - if self['state'] in ('status', 'both'): - cmd = self['statuscommand'] - if callable(cmd): - cmd(statusHelp) - - def clearstatus(self): - self.showstatus(None) - - def _state(self): - if self['state'] not in ('both', 'balloon', 'status', 'none'): - raise ValueError, 'bad state option ' + repr(self['state']) + \ - ': should be one of \'both\', \'balloon\', ' + \ - '\'status\' or \'none\'' - - def _relmouse(self): - if self['relmouse'] not in ('both', 'x', 'y', 'none'): - raise ValueError, 'bad relmouse option ' + repr(self['relmouse'])+ \ - ': should be one of \'both\', \'x\', ' + '\'y\' or \'none\'' - - def _enter(self, event, widget, statusHelp, balloonHelp, isItem): - - # Do not display balloon if mouse button is pressed. This - # will only occur if the button was pressed inside a widget, - # then the mouse moved out of and then back into the widget, - # with the button still held down. The number 0x1f00 is the - # button mask for the 5 possible buttons in X. - buttonPressed = (event.state & 0x1f00) != 0 - - if not buttonPressed and balloonHelp is not None and \ - self['state'] in ('balloon', 'both'): - if self._timer is not None: - self.after_cancel(self._timer) - self._timer = None - - self._timer = self.after(self['initwait'], - lambda self = self, widget = widget, help = balloonHelp, - isItem = isItem: - self._showBalloon(widget, help, isItem)) - - if isItem: - if hasattr(widget, 'canvasx'): - # The widget is a canvas. - item = widget.find_withtag('current') - if len(item) > 0: - item = item[0] - else: - item = None - self._currentTrigger = (widget, item) - else: - # The widget is a text widget. - self._currentTrigger = (widget, event.x, event.y) - else: - self._currentTrigger = (widget,) - - self.showstatus(statusHelp) - - def _leave(self, event): - if self._timer is not None: - self.after_cancel(self._timer) - self._timer = None - self.withdraw() - self.clearstatus() - self._currentTrigger = None - - def _destroy(self, event): - - # Only withdraw the balloon and cancel the timer if the widget - # being destroyed is the widget that triggered the balloon. - # Note that in a Tkinter Destroy event, the widget field is a - # string and not a widget as usual. - - if self._currentTrigger is None: - # The balloon is not currently being displayed - return - - if len(self._currentTrigger) == 1: - # The current trigger is a widget (not an item) - triggerWidget = self._currentTrigger[0] - if str(triggerWidget) == event.widget: - if self._timer is not None: - self.after_cancel(self._timer) - self._timer = None - self.withdraw() - self.clearstatus() - self._currentTrigger = None - - def _buttonpress(self, event): - if self._timer is not None: - self.after_cancel(self._timer) - self._timer = None - self.withdraw() - self._currentTrigger = None - - def _showBalloon(self, widget, balloonHelp, isItem): - - self._label.configure(text = balloonHelp) - - # First, display the balloon offscreen to get dimensions. - screenWidth = self.winfo_screenwidth() - screenHeight = self.winfo_screenheight() - self.geometry('+%d+0' % (screenWidth + 1)) - self.update_idletasks() - - if isItem: - # Get the bounding box of the current item. - bbox = widget.bbox('current') - if bbox is None: - # The item that triggered the balloon has disappeared, - # perhaps by a user's timer event that occured between - # the event and the 'initwait' timer calling - # this method. - return - - # The widget is either a text or canvas. The meaning of - # the values returned by the bbox method is different for - # each, so use the existence of the 'canvasx' method to - # distinguish between them. - if hasattr(widget, 'canvasx'): - # The widget is a canvas. Place balloon under canvas - # item. The positions returned by bbox are relative - # to the entire canvas, not just the visible part, so - # need to convert to window coordinates. - leftrel = bbox[0] - widget.canvasx(0) - toprel = bbox[1] - widget.canvasy(0) - bottomrel = bbox[3] - widget.canvasy(0) - else: - # The widget is a text widget. Place balloon under - # the character closest to the mouse. The positions - # returned by bbox are relative to the text widget - # window (ie the visible part of the text only). - leftrel = bbox[0] - toprel = bbox[1] - bottomrel = bbox[1] + bbox[3] - else: - leftrel = 0 - toprel = 0 - bottomrel = widget.winfo_height() - - xpointer, ypointer = widget.winfo_pointerxy() # -1 if off screen - - if xpointer >= 0 and self['relmouse'] in ('both', 'x'): - x = xpointer - else: - x = leftrel + widget.winfo_rootx() - x = x + self['xoffset'] - - if ypointer >= 0 and self['relmouse'] in ('both', 'y'): - y = ypointer - else: - y = bottomrel + widget.winfo_rooty() - y = y + self['yoffset'] - - edges = (string.atoi(str(self.cget('hull_highlightthickness'))) + - string.atoi(str(self.cget('hull_borderwidth')))) * 2 - if x + self._label.winfo_reqwidth() + edges > screenWidth: - x = screenWidth - self._label.winfo_reqwidth() - edges - - if y + self._label.winfo_reqheight() + edges > screenHeight: - if ypointer >= 0 and self['relmouse'] in ('both', 'y'): - y = ypointer - else: - y = toprel + widget.winfo_rooty() - y = y - self._label.winfo_reqheight() - self['yoffset'] - edges - - Pmw.setgeometryanddeiconify(self, '+%d+%d' % (x, y)) diff --git a/Pmw/Pmw_1_2/lib/PmwBase.py b/Pmw/Pmw_1_2/lib/PmwBase.py deleted file mode 100644 index da38e9a4..00000000 --- a/Pmw/Pmw_1_2/lib/PmwBase.py +++ /dev/null @@ -1,1933 +0,0 @@ -# Pmw megawidget base classes. - -# This module provides a foundation for building megawidgets. It -# contains the MegaArchetype class which manages component widgets and -# configuration options. Also provided are the MegaToplevel and -# MegaWidget classes, derived from the MegaArchetype class. The -# MegaToplevel class contains a Tkinter Toplevel widget to act as the -# container of the megawidget. This is used as the base class of all -# megawidgets that are contained in their own top level window, such -# as a Dialog window. The MegaWidget class contains a Tkinter Frame -# to act as the container of the megawidget. This is used as the base -# class of all other megawidgets, such as a ComboBox or ButtonBox. -# -# Megawidgets are built by creating a class that inherits from either -# the MegaToplevel or MegaWidget class. - -import os -import string -import sys -import traceback -import types -import Tkinter - -# Special values used in index() methods of several megawidgets. -END = ['end'] -SELECT = ['select'] -DEFAULT = ['default'] - -# Constant used to indicate that an option can only be set by a call -# to the constructor. -INITOPT = ['initopt'] -_DEFAULT_OPTION_VALUE = ['default_option_value'] -_useTkOptionDb = 0 - -# Symbolic constants for the indexes into an optionInfo list. -_OPT_DEFAULT = 0 -_OPT_VALUE = 1 -_OPT_FUNCTION = 2 - -# Stacks - -_busyStack = [] - # Stack which tracks nested calls to show/hidebusycursor (called - # either directly or from activate()/deactivate()). Each element - # is a dictionary containing: - # 'newBusyWindows' : List of windows which had busy_hold called - # on them during a call to showbusycursor(). - # The corresponding call to hidebusycursor() - # will call busy_release on these windows. - # 'busyFocus' : The blt _Busy window which showbusycursor() - # set the focus to. - # 'previousFocus' : The focus as it was when showbusycursor() - # was called. The corresponding call to - # hidebusycursor() will restore this focus if - # the focus has not been changed from busyFocus. - -_grabStack = [] - # Stack of grabbed windows. It tracks calls to push/popgrab() - # (called either directly or from activate()/deactivate()). The - # window on the top of the stack is the window currently with the - # grab. Each element is a dictionary containing: - # 'grabWindow' : The window grabbed by pushgrab(). The - # corresponding call to popgrab() will release - # the grab on this window and restore the grab - # on the next window in the stack (if there is one). - # 'globalMode' : True if the grabWindow was grabbed with a - # global grab, false if the grab was local - # and 'nograb' if no grab was performed. - # 'previousFocus' : The focus as it was when pushgrab() - # was called. The corresponding call to - # popgrab() will restore this focus. - # 'deactivateFunction' : - # The function to call (usually grabWindow.deactivate) if - # popgrab() is called (usually from a deactivate() method) - # on a window which is not at the top of the stack (that is, - # does not have the grab or focus). For example, if a modal - # dialog is deleted by the window manager or deactivated by - # a timer. In this case, all dialogs above and including - # this one are deactivated, starting at the top of the - # stack. - - # Note that when dealing with focus windows, the name of the Tk - # widget is used, since it may be the '_Busy' window, which has no - # python instance associated with it. - -#============================================================================= - -# Functions used to forward methods from a class to a component. - -# Fill in a flattened method resolution dictionary for a class (attributes are -# filtered out). Flattening honours the MI method resolution rules -# (depth-first search of bases in order). The dictionary has method names -# for keys and functions for values. -def __methodDict(cls, dict): - - # the strategy is to traverse the class in the _reverse_ of the normal - # order, and overwrite any duplicates. - baseList = list(cls.__bases__) - baseList.reverse() - - # do bases in reverse order, so first base overrides last base - for super in baseList: - __methodDict(super, dict) - - # do my methods last to override base classes - for key, value in cls.__dict__.items(): - # ignore class attributes - if type(value) == types.FunctionType: - dict[key] = value - -def __methods(cls): - # Return all method names for a class. - - # Return all method names for a class (attributes are filtered - # out). Base classes are searched recursively. - - dict = {} - __methodDict(cls, dict) - return dict.keys() - -# Function body to resolve a forwarding given the target method name and the -# attribute name. The resulting lambda requires only self, but will forward -# any other parameters. -__stringBody = ( - 'def %(method)s(this, *args, **kw): return ' + - 'apply(this.%(attribute)s.%(method)s, args, kw)') - -# Get a unique id -__counter = 0 -def __unique(): - global __counter - __counter = __counter + 1 - return str(__counter) - -# Function body to resolve a forwarding given the target method name and the -# index of the resolution function. The resulting lambda requires only self, -# but will forward any other parameters. The target instance is identified -# by invoking the resolution function. -__funcBody = ( - 'def %(method)s(this, *args, **kw): return ' + - 'apply(this.%(forwardFunc)s().%(method)s, args, kw)') - -def forwardmethods(fromClass, toClass, toPart, exclude = ()): - # Forward all methods from one class to another. - - # Forwarders will be created in fromClass to forward method - # invocations to toClass. The methods to be forwarded are - # identified by flattening the interface of toClass, and excluding - # methods identified in the exclude list. Methods already defined - # in fromClass, or special methods with one or more leading or - # trailing underscores will not be forwarded. - - # For a given object of class fromClass, the corresponding toClass - # object is identified using toPart. This can either be a String - # denoting an attribute of fromClass objects, or a function taking - # a fromClass object and returning a toClass object. - - # Example: - # class MyClass: - # ... - # def __init__(self): - # ... - # self.__target = TargetClass() - # ... - # def findtarget(self): - # return self.__target - # forwardmethods(MyClass, TargetClass, '__target', ['dangerous1', 'dangerous2']) - # # ...or... - # forwardmethods(MyClass, TargetClass, MyClass.findtarget, - # ['dangerous1', 'dangerous2']) - - # In both cases, all TargetClass methods will be forwarded from - # MyClass except for dangerous1, dangerous2, special methods like - # __str__, and pre-existing methods like findtarget. - - - # Allow an attribute name (String) or a function to determine the instance - if type(toPart) != types.StringType: - - # check that it is something like a function - if callable(toPart): - - # If a method is passed, use the function within it - if hasattr(toPart, 'im_func'): - toPart = toPart.im_func - - # After this is set up, forwarders in this class will use - # the forwarding function. The forwarding function name is - # guaranteed to be unique, so that it can't be hidden by subclasses - forwardName = '__fwdfunc__' + __unique() - fromClass.__dict__[forwardName] = toPart - - # It's not a valid type - else: - raise TypeError, 'toPart must be attribute name, function or method' - - # get the full set of candidate methods - dict = {} - __methodDict(toClass, dict) - - # discard special methods - for ex in dict.keys(): - if ex[:1] == '_' or ex[-1:] == '_': - del dict[ex] - # discard dangerous methods supplied by the caller - for ex in exclude: - if dict.has_key(ex): - del dict[ex] - # discard methods already defined in fromClass - for ex in __methods(fromClass): - if dict.has_key(ex): - del dict[ex] - - for method, func in dict.items(): - d = {'method': method, 'func': func} - if type(toPart) == types.StringType: - execString = \ - __stringBody % {'method' : method, 'attribute' : toPart} - else: - execString = \ - __funcBody % {'forwardFunc' : forwardName, 'method' : method} - - exec execString in d - - # this creates a method - fromClass.__dict__[method] = d[method] - -#============================================================================= - -def setgeometryanddeiconify(window, geom): - # To avoid flashes on X and to position the window correctly on NT - # (caused by Tk bugs). - - if os.name == 'nt' or \ - (os.name == 'posix' and sys.platform[:6] == 'cygwin'): - # Require overrideredirect trick to stop window frame - # appearing momentarily. - redirect = window.overrideredirect() - if not redirect: - window.overrideredirect(1) - window.deiconify() - if geom is not None: - window.geometry(geom) - # Call update_idletasks to ensure NT moves the window to the - # correct position it is raised. - window.update_idletasks() - window.tkraise() - if not redirect: - window.overrideredirect(0) - else: - if geom is not None: - window.geometry(geom) - - # Problem!? Which way around should the following two calls - # go? If deiconify() is called first then I get complaints - # from people using the enlightenment or sawfish window - # managers that when a dialog is activated it takes about 2 - # seconds for the contents of the window to appear. But if - # tkraise() is called first then I get complaints from people - # using the twm window manager that when a dialog is activated - # it appears in the top right corner of the screen and also - # takes about 2 seconds to appear. - - #window.tkraise() - # Call update_idletasks to ensure certain window managers (eg: - # enlightenment and sawfish) do not cause Tk to delay for - # about two seconds before displaying window. - #window.update_idletasks() - #window.deiconify() - - window.deiconify() - if window.overrideredirect(): - # The window is not under the control of the window manager - # and so we need to raise it ourselves. - window.tkraise() - -#============================================================================= - -class MegaArchetype: - # Megawidget abstract root class. - - # This class provides methods which are inherited by classes - # implementing useful bases (this class doesn't provide a - # container widget inside which the megawidget can be built). - - def __init__(self, parent = None, hullClass = None): - - # Mapping from each megawidget option to a list of information - # about the option - # - default value - # - current value - # - function to call when the option is initialised in the - # call to initialiseoptions() in the constructor or - # modified via configure(). If this is INITOPT, the - # option is an initialisation option (an option that can - # be set by the call to the constructor but can not be - # used with configure). - # This mapping is not initialised here, but in the call to - # defineoptions() which precedes construction of this base class. - # - # self._optionInfo = {} - - # Mapping from each component name to a tuple of information - # about the component. - # - component widget instance - # - configure function of widget instance - # - the class of the widget (Frame, EntryField, etc) - # - cget function of widget instance - # - the name of the component group of this component, if any - self.__componentInfo = {} - - # Mapping from alias names to the names of components or - # sub-components. - self.__componentAliases = {} - - # Contains information about the keywords provided to the - # constructor. It is a mapping from the keyword to a tuple - # containing: - # - value of keyword - # - a boolean indicating if the keyword has been used. - # A keyword is used if, during the construction of a megawidget, - # - it is defined in a call to defineoptions() or addoptions(), or - # - it references, by name, a component of the megawidget, or - # - it references, by group, at least one component - # At the end of megawidget construction, a call is made to - # initialiseoptions() which reports an error if there are - # unused options given to the constructor. - # - # After megawidget construction, the dictionary contains - # keywords which refer to a dynamic component group, so that - # these components can be created after megawidget - # construction and still use the group options given to the - # constructor. - # - # self._constructorKeywords = {} - - # List of dynamic component groups. If a group is included in - # this list, then it not an error if a keyword argument for - # the group is given to the constructor or to configure(), but - # no components with this group have been created. - # self._dynamicGroups = () - - if hullClass is None: - self._hull = None - else: - if parent is None: - parent = Tkinter._default_root - - # Create the hull. - self._hull = self.createcomponent('hull', - (), None, - hullClass, (parent,)) - _hullToMegaWidget[self._hull] = self - - if _useTkOptionDb: - # Now that a widget has been created, query the Tk - # option database to get the default values for the - # options which have not been set in the call to the - # constructor. This assumes that defineoptions() is - # called before the __init__(). - option_get = self.option_get - _VALUE = _OPT_VALUE - _DEFAULT = _OPT_DEFAULT - for name, info in self._optionInfo.items(): - value = info[_VALUE] - if value is _DEFAULT_OPTION_VALUE: - resourceClass = string.upper(name[0]) + name[1:] - value = option_get(name, resourceClass) - if value != '': - try: - # Convert the string to int/float/tuple, etc - value = eval(value, {'__builtins__': {}}) - except: - pass - info[_VALUE] = value - else: - info[_VALUE] = info[_DEFAULT] - - def destroy(self): - # Clean up optionInfo in case it contains circular references - # in the function field, such as self._settitle in class - # MegaToplevel. - - self._optionInfo = {} - if self._hull is not None: - del _hullToMegaWidget[self._hull] - self._hull.destroy() - - #====================================================================== - # Methods used (mainly) during the construction of the megawidget. - - def defineoptions(self, keywords, optionDefs, dynamicGroups = ()): - # Create options, providing the default value and the method - # to call when the value is changed. If any option created by - # base classes has the same name as one in , the - # base class's value and function will be overriden. - - # This should be called before the constructor of the base - # class, so that default values defined in the derived class - # override those in the base class. - - if not hasattr(self, '_constructorKeywords'): - # First time defineoptions has been called. - tmp = {} - for option, value in keywords.items(): - tmp[option] = [value, 0] - self._constructorKeywords = tmp - self._optionInfo = {} - self._initialiseoptions_counter = 0 - self._initialiseoptions_counter = self._initialiseoptions_counter + 1 - - if not hasattr(self, '_dynamicGroups'): - self._dynamicGroups = () - self._dynamicGroups = self._dynamicGroups + tuple(dynamicGroups) - self.addoptions(optionDefs) - - def addoptions(self, optionDefs): - # Add additional options, providing the default value and the - # method to call when the value is changed. See - # "defineoptions" for more details - - # optimisations: - optionInfo = self._optionInfo - optionInfo_has_key = optionInfo.has_key - keywords = self._constructorKeywords - keywords_has_key = keywords.has_key - FUNCTION = _OPT_FUNCTION - - for name, default, function in optionDefs: - if '_' not in name: - # The option will already exist if it has been defined - # in a derived class. In this case, do not override the - # default value of the option or the callback function - # if it is not None. - if not optionInfo_has_key(name): - if keywords_has_key(name): - value = keywords[name][0] - optionInfo[name] = [default, value, function] - del keywords[name] - else: - if _useTkOptionDb: - optionInfo[name] = \ - [default, _DEFAULT_OPTION_VALUE, function] - else: - optionInfo[name] = [default, default, function] - elif optionInfo[name][FUNCTION] is None: - optionInfo[name][FUNCTION] = function - else: - # This option is of the form "component_option". If this is - # not already defined in self._constructorKeywords add it. - # This allows a derived class to override the default value - # of an option of a component of a base class. - if not keywords_has_key(name): - keywords[name] = [default, 0] - - def createcomponent(self, componentName, componentAliases, - componentGroup, widgetClass, *widgetArgs, **kw): - # Create a component (during construction or later). - - if self.__componentInfo.has_key(componentName): - raise ValueError, 'Component "%s" already exists' % componentName - - if '_' in componentName: - raise ValueError, \ - 'Component name "%s" must not contain "_"' % componentName - - if hasattr(self, '_constructorKeywords'): - keywords = self._constructorKeywords - else: - keywords = {} - for alias, component in componentAliases: - # Create aliases to the component and its sub-components. - index = string.find(component, '_') - if index < 0: - self.__componentAliases[alias] = (component, None) - else: - mainComponent = component[:index] - subComponent = component[(index + 1):] - self.__componentAliases[alias] = (mainComponent, subComponent) - - # Remove aliases from the constructor keyword arguments by - # replacing any keyword arguments that begin with *alias* - # with corresponding keys beginning with *component*. - - alias = alias + '_' - aliasLen = len(alias) - for option in keywords.keys(): - if len(option) > aliasLen and option[:aliasLen] == alias: - newkey = component + '_' + option[aliasLen:] - keywords[newkey] = keywords[option] - del keywords[option] - - componentPrefix = componentName + '_' - nameLen = len(componentPrefix) - for option in keywords.keys(): - if len(option) > nameLen and option[:nameLen] == componentPrefix: - # The keyword argument refers to this component, so add - # this to the options to use when constructing the widget. - kw[option[nameLen:]] = keywords[option][0] - del keywords[option] - else: - # Check if this keyword argument refers to the group - # of this component. If so, add this to the options - # to use when constructing the widget. Mark the - # keyword argument as being used, but do not remove it - # since it may be required when creating another - # component. - index = string.find(option, '_') - if index >= 0 and componentGroup == option[:index]: - rest = option[(index + 1):] - kw[rest] = keywords[option][0] - keywords[option][1] = 1 - - if kw.has_key('pyclass'): - widgetClass = kw['pyclass'] - del kw['pyclass'] - if widgetClass is None: - return None - if len(widgetArgs) == 1 and type(widgetArgs[0]) == types.TupleType: - # Arguments to the constructor can be specified as either - # multiple trailing arguments to createcomponent() or as a - # single tuple argument. - widgetArgs = widgetArgs[0] - widget = apply(widgetClass, widgetArgs, kw) - componentClass = widget.__class__.__name__ - self.__componentInfo[componentName] = (widget, widget.configure, - componentClass, widget.cget, componentGroup) - - return widget - - def destroycomponent(self, name): - # Remove a megawidget component. - - # This command is for use by megawidget designers to destroy a - # megawidget component. - - self.__componentInfo[name][0].destroy() - del self.__componentInfo[name] - - def createlabel(self, parent, childCols = 1, childRows = 1): - - labelpos = self['labelpos'] - labelmargin = self['labelmargin'] - if labelpos is None: - return - - label = self.createcomponent('label', - (), None, - Tkinter.Label, (parent,)) - - if labelpos[0] in 'ns': - # vertical layout - if labelpos[0] == 'n': - row = 0 - margin = 1 - else: - row = childRows + 3 - margin = row - 1 - label.grid(column=2, row=row, columnspan=childCols, sticky=labelpos) - parent.grid_rowconfigure(margin, minsize=labelmargin) - else: - # horizontal layout - if labelpos[0] == 'w': - col = 0 - margin = 1 - else: - col = childCols + 3 - margin = col - 1 - label.grid(column=col, row=2, rowspan=childRows, sticky=labelpos) - parent.grid_columnconfigure(margin, minsize=labelmargin) - - def initialiseoptions(self, dummy = None): - self._initialiseoptions_counter = self._initialiseoptions_counter - 1 - if self._initialiseoptions_counter == 0: - unusedOptions = [] - keywords = self._constructorKeywords - for name in keywords.keys(): - used = keywords[name][1] - if not used: - # This keyword argument has not been used. If it - # does not refer to a dynamic group, mark it as - # unused. - index = string.find(name, '_') - if index < 0 or name[:index] not in self._dynamicGroups: - unusedOptions.append(name) - if len(unusedOptions) > 0: - if len(unusedOptions) == 1: - text = 'Unknown option "' - else: - text = 'Unknown options "' - raise KeyError, text + string.join(unusedOptions, ', ') + \ - '" for ' + self.__class__.__name__ - - # Call the configuration callback function for every option. - FUNCTION = _OPT_FUNCTION - for info in self._optionInfo.values(): - func = info[FUNCTION] - if func is not None and func is not INITOPT: - func() - - #====================================================================== - # Method used to configure the megawidget. - - def configure(self, option=None, **kw): - # Query or configure the megawidget options. - # - # If not empty, *kw* is a dictionary giving new - # values for some of the options of this megawidget or its - # components. For options defined for this megawidget, set - # the value of the option to the new value and call the - # configuration callback function, if any. For options of the - # form _