wxPython - Boutons

Le widget bouton est le plus largement utilisé dans toute interface graphique. Il capture l'événement de clic généré par l'utilisateur. Son utilisation la plus évidente est de déclencher une fonction de gestionnaire qui lui est liée.

La bibliothèque de classes wxPython fournit différents types de boutons. Il y a un bouton simple et traditionnel,wx.Buttonobjet de classe, qui contient du texte comme légende. Un bouton à deux états est également disponible, nommé commewx.ToggleButton. Son état enfoncé ou enfoncé peut être identifié par la fonction de gestionnaire d'événements.

Un autre type de bouton, wx.BitmapButton affiche un bitmap (image) sous forme d'icône sur son visage.

Le constructeur de la classe wx.Button et de la classe wx.ToggleButton prend les arguments suivants -

Wx.Button(parent, id, label, pos, size, style)

Voici quelques méthodes importantes de la classe wx.Button -

SN Méthodes et description
1

SetLabel()

Définit la légende du bouton par programmation

2

GetLabel()

Renvoie la légende du bouton

3

SetDefault()

Le bouton est défini par défaut pour la fenêtre de niveau supérieur. Émule l'événement de clic en appuyant sur la touche Entrée

Deux méthodes importantes de la classe wx.ToggleButton sont -

SN Méthodes et description
1

GetValue()

Renvoie l'état du bouton bascule (marche / arrêt)

2

SetValue()

Définit l'état du bouton par programmation

Pour créer un bouton bitmap, tout d'abord, un objet bitmap doit être construit à partir d'un fichier image.

La variante suivante du constructeur de classe wx.Bitmap est la plus couramment utilisée -

Wx.Bitmap(fiiename, wx.BITMAP_TYPE)

Certaines des constantes de type bitmap prédéfinies sont -

wx.BITMAP_TYPE_BMP
wx.BITMAP_TYPE_ICO
wx.BITMAP_TYPE_CUR
wx.BITMAP_TYPE_TIFF
wx.BITMAP_TYPE_TIF
wx.BITMAP_TYPE_GIF
wx.BITMAP_TYPE_PNG
wx.BITMAP_TYPE_JPEG
wx.BITMAP_TYPE_PCX
wx.BITMAP_TYPE_ICON
wx.BITMAP_TYPE_ANY

Cet objet bitmap est utilisé comme l'un des paramètres du constructeur de classe wx.BitmapButton.

Wx.BitmapButton(parent, id, bitmap, pos, size, style)

Sur certaines plates-formes OS, le bouton bitmap peut afficher à la fois le bitmap et l'étiquette. Les méthodes SetLabel () affectent la légende. Sur d'autres plateformes, il sert de label interne.

Le bouton normal ainsi que le bouton bitmap émettent un wx.CommandEvent. Le classeur EVT_BUTTON lui associe une fonction de gestionnaire.

Le bouton bascule en revanche utilise le classeur wx.TOGGLEBUTTON pour la gestion des événements.

Dans l'exemple suivant, les boutons des trois types sont placés dans un gabarit vertical d'un panneau.

L'objet bouton simple est créé à l'aide de l'instruction -

self.btn = wx.Button(panel, -1, "click Me")

Le bouton bascule est construit par l'instruction suivante -

self.tbtn = wx.ToggleButton(panel , -1, "click to on")

Ces boutons sont ajoutés au calibreur vertical en utilisant les instructions suivantes -

vbox.Add(self.btn,0,wx.ALIGN_CENTER) 
vbox.Add(self.tbtn,0,wx.EXPAND|wx.ALIGN_CENTER)

Note - En raison de l'indicateur wx.EXPAND, le bouton bascule occupe toute la largeur du cadre.

En utilisant les classeurs EVT_BUTTON et EVT_TOGGLEBUTTON, ils sont associés aux gestionnaires respectifs.

self.btn.Bind(wx.EVT_BUTTON,self.OnClicked) 
self.tbtn.Bind(wx.EVT_TOGGLEBUTTON,self.OnToggle)

Trois boutons bitmap sont ajoutés dans un gabarit horizontal. Ces boutons affichent une image sous forme d'icône en guise de légende.

bmp = wx.Bitmap("NEW.BMP", wx.BITMAP_TYPE_BMP) 
self.bmpbtn = wx.BitmapButton(panel, id = wx.ID_ANY, bitmap = bmp,
   size = (bmp.GetWidth()+10, bmp.GetHeight()+10))
  
bmp1 = wx.Bitmap("OPEN.BMP", wx.BITMAP_TYPE_BMP) 
self.bmpbtn1 = wx.BitmapButton(panel, id = wx.ID_ANY, bitmap = bmp1,
   size = (bmp.GetWidth()+10, bmp.GetHeight()+10))
  
bmp2 = wx.Bitmap("SAVE.BMP", wx.BITMAP_TYPE_BMP) 
self.bmpbtn2 = wx.BitmapButton(panel, id = wx.ID_ANY, bitmap = bmp2,
   size = (bmp.GetWidth()+10, bmp.GetHeight()+10))

L'événement Click de ces trois boutons est dirigé vers la méthode OnClicked ().

self.bmpbtn.Bind(wx.EVT_BUTTON, self.OnClicked) 
self.bmpbtn1.Bind(wx.EVT_BUTTON, self.OnClicked) 
self.bmpbtn2.Bind(wx.EVT_BUTTON, self.OnClicked)

Les étiquettes internes de ces boutons sont respectivement réglées sur NEW, OPEN et SAVE.

La fonction de gestionnaire d'événements OnClicked () récupère le libellé du bouton source, qui a provoqué l'événement de clic. Cette étiquette est imprimée sur la console.

def OnClicked(self, event): 
   btn = event.GetEventObject().GetLabel() 
   print "Label of pressed button = ",btn

Le gestionnaire d'événements OnToggle () est déclenché lorsque le bouton bascule est cliqué. Son état est lu par la méthode GetValue () et en conséquence, la légende du bouton est définie.

def OnToggle(self,event): 
   state = event.GetEventObject().GetValue() 
   if state == True: 
      print "off" 
      event.GetEventObject().SetLabel("click to off") 
   else: 
      print "on" 
      event.GetEventObject().SetLabel("click to on")

La liste complète des codes est la suivante -

import wx 
class Mywin(wx.Frame): 
   def __init__(self, parent, title): 
      super(Mywin, self).__init__(parent, title = title,size = (200,150))  
      panel = wx.Panel(self) 
      vbox = wx.BoxSizer(wx.VERTICAL) 
         
      self.btn = wx.Button(panel,-1,"click Me") 
      vbox.Add(self.btn,0,wx.ALIGN_CENTER) 
      self.btn.Bind(wx.EVT_BUTTON,self.OnClicked) 
         
      self.tbtn = wx.ToggleButton(panel , -1, "click to on") 
      vbox.Add(self.tbtn,0,wx.EXPAND|wx.ALIGN_CENTER) 
      self.tbtn.Bind(wx.EVT_TOGGLEBUTTON,self.OnToggle) 
         
      hbox = wx.BoxSizer(wx.HORIZONTAL) 
         
      bmp = wx.Bitmap("NEW.BMP", wx.BITMAP_TYPE_BMP) 
      self.bmpbtn = wx.BitmapButton(panel, id = wx.ID_ANY, bitmap = bmp,
         size = (bmp.GetWidth()+10, bmp.GetHeight()+10)) 
			
      hbox.Add(self.bmpbtn,0,wx.ALIGN_CENTER) 
      self.bmpbtn.Bind(wx.EVT_BUTTON,self.OnClicked) 
      self.bmpbtn.SetLabel("NEW") 
         
      bmp1 = wx.Bitmap("OPEN.BMP", wx.BITMAP_TYPE_BMP) 
      self.bmpbtn1 = wx.BitmapButton(panel, id = wx.ID_ANY, bitmap = bmp1,
         size = (bmp.GetWidth()+10, bmp.GetHeight()+10)) 
			
      hbox.Add(self.bmpbtn1,0,wx.ALIGN_CENTER) 
      self.bmpbtn1.Bind(wx.EVT_BUTTON,self.OnClicked) 
      self.bmpbtn1.SetLabel("OPEN") 
         
      bmp2 = wx.Bitmap("SAVE.BMP", wx.BITMAP_TYPE_BMP) 
      self.bmpbtn2 = wx.BitmapButton(panel, id = wx.ID_ANY, bitmap = bmp2,
         size = (bmp.GetWidth()+10, bmp.GetHeight()+10))
			
      hbox.Add(self.bmpbtn2,0,wx.ALIGN_CENTER) 
      self.bmpbtn2.Bind(wx.EVT_BUTTON,self.OnClicked)
      self.bmpbtn2.SetLabel("SAVE") 
         
      vbox.Add(hbox,1,wx.ALIGN_CENTER) 
      panel.SetSizer(vbox) 
        
      self.Centre() 
      self.Show() 
      self.Fit()  
		
   def OnClicked(self, event): 
      btn = event.GetEventObject().GetLabel() 
      print "Label of pressed button = ",btn 
		
   def OnToggle(self,event): 
      state = event.GetEventObject().GetValue() 
		
      if state == True: 
         print "Toggle button state off" 
         event.GetEventObject().SetLabel("click to off") 
      else: 
         print " Toggle button state on" 
         event.GetEventObject().SetLabel("click to on") 
             
app = wx.App() 
Mywin(None,  'Button demo') 
app.MainLoop()

Le code ci-dessus produit la sortie suivante -

Libellé du bouton enfoncé = cliquez sur Moi

Désactiver l'état du bouton

Activer l'état du bouton

Libellé du bouton enfoncé = NOUVEAU

Libellé du bouton enfoncé = OPEN

Libellé du bouton enfoncé = SAVE