change parameters to button in wxpython

0

Hello, I have a question about how to change parameters to a button in wxpython. I explain: I have a window with a drop-down list with some colors and I have a button below that says "OK"

The idea is that the user select some color from the list and then click on the "OK" button.

If the user selects the white color, a pop-up should be opened with an error message. If you select any other color you must close the window. Here is the code in python: import wx

class ventana(wx.App):


    def OnInit(self):
        frame = crear_ventana()
        frame.Show(True)
        frame.Centre()
        return True

####SI EL USUARIO SELECCIONA BLANCO Y LE DA OK DEBE APARECER ESTA 
VENTAN:#######


class ventana_error(wx.Dialog):

    def __init__(self, padre):

        wx.Dialog.__init__(self, padre, wx.NewId(),
                           title="Error", size=(300, 100))
        panel = wx.Panel(self, -1)
        boton = wx.Button(panel, label="entendido",
                      pos=(125, 37), size=(70, 25))
        boton.Bind(wx.EVT_BUTTON, self.llamar)
        self.Centre()
        normal = wx.StaticText(
            panel, -1, "Seleccione otro color", pos=(75, 15), style=wx.ALL)
        # self.entrada_texto=wx.TextCtrl(panel,value="",pos=(5,27),size= 
               (5,5),style=wx.TE_LEFT)

    def llamar(self, event):
        self.Close(True)


#################VENTANA PRINCIPAL: ##################

class crear_ventana(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, -1, title="Seleccione colores", size= 
          (200, 200),
                      pos=(100, 10), style=wx.DEFAULT_FRAME_STYLE & ~ 
  (wx.RESIZE_BORDER | wx.MAXIMIZE_BOX | wx.MINIMIZE_BOX | wx.CLOSE_BOX))
       panel1 = wx.Panel(self, -1)

        boton1 = wx.Button(panel1, label="OK",
                       pos=(50, 100), size=(50, 25))

        opciones = [u"Blanco", u"Rojo", u"Verde"]
        self.opciones = wx.Choice(
           panel1, wx.ID_ANY, choices=opciones, pos=(50, 50), size=(100, 
             25))
    self.opciones.SetSelection(-1)

    #####AQUI ESTA EL PROBLERMA:######
    boton1.Bind(wx.EVT_BUTTON, self.llamar_ventana1)
    # Lo que necesito es cambiar ese llamar_ventana1
    # por llamar_ventana2 pero dependiendo de lo que el
    # usuario seleccione

    dec = self.opciones.Bind(
        wx.EVT_CHOICE, self.Choice)  # esto se me ocurrio
    # pero resulta que solo funciona una vez al ejecutarse
    # tal vez que me devuelva un valor distinto cada vez que
    # el usuario cambie de seleccion
    # dec almacena eso que el usuario selecciona

    print("dec: ")
    print(dec)

    def Choice(self, event):  # Esta es la funcion para verificar lo que se 
    selecciono
      global numerox

       opcion_seleccionada = self.opciones.GetStringSelection()
       opcion_seleccionada_uno = self.opciones.GetSelection()
       print(opcion_seleccionada)
       print(opcion_seleccionada_uno)
       return opcion_seleccionada_uno

     def llamar_ventana1(self, event):  # si el usuario selecciona blanco
        # llamar a esta funcion
        ventana2 = ventana_error(self)
        ventana2.ShowModal()
        ventana2.Destroy()


     def llamar_ventana2(self, event):  # si selecciona otro color llamar a 
          esta funcion
          self.Destroy()


app1 = ventana(0)
app1.MainLoop()

If someone else knows how to do that, he explains. I'll be here all the time thanks:)

    
asked by metamax 07.07.2018 в 23:35
source

1 answer

0

In principle you're on the right track, but instead of trying to change the callback associated with the button depending on the selected option, it's simpler to use a wrapper. Since the action must take place when the button is pressed, not when the selection occurs, simply use a conditional in the callback and call one method or another depending on the current option of Choice :

import wx



class App(wx.App):

    def OnInit(self):
        frame = SeleccionColores()
        frame.Show(True)
        frame.Centre()
        return True


class VentanaError(wx.Dialog):

    def __init__(self, padre, mensage=""):

        super().__init__(padre, wx.NewId(),
                         title="Error", size=(300, 100)
                         )
        panel = wx.Panel(self, -1)
        boton = wx.Button(panel, label="entendido", size=(70, 25))
        msg = wx.StaticText(panel, -1, mensage, style=wx.ALL)
        main_sizer = wx.BoxSizer(wx.VERTICAL)
        main_sizer.AddStretchSpacer()
        main_sizer.Add(msg, 0, wx.CENTER)
        main_sizer.AddStretchSpacer()
        main_sizer.Add(boton, 2, wx.CENTER)
        main_sizer.AddStretchSpacer()

        panel.SetSizer(main_sizer)
        boton.Bind(wx.EVT_BUTTON, self.cerrar)
        self.Centre()

    def cerrar(self, event):
        self.Close(True)


class SeleccionColores(wx.Frame):

    def __init__(self):
        super().__init__(None, -1, title="Seleccione colores",
                         size= (200, 200), pos=(100, 10),
                         style=(wx.DEFAULT_FRAME_STYLE & ~ 
                                (wx.RESIZE_BORDER | wx.MAXIMIZE_BOX | 
                                 wx.MINIMIZE_BOX | wx.CLOSE_BOX)))


        panel = wx.Panel(self, -1)
        boton = wx.Button(panel, label="OK", pos=(50, 100), size=(50, 25))

        opciones = ["Blanco", "Rojo", "Verde"]
        self.opciones = wx.Choice(panel, wx.ID_ANY, choices=opciones,
                                  pos=(50, 50), size=(100, 35)
                                  )
        self.opciones.SetSelection(-1)
        boton.Bind(wx.EVT_BUTTON, self.seleccion)

    def seleccion(self, event):
        opcion_seleccionada = self.opciones.GetStringSelection()
        if not opcion_seleccionada:
            self.mostrar_dialogo_error("Seleccione un color")
        elif opcion_seleccionada == "Blanco":
            self.mostrar_dialogo_error("Seleccione otro color")
        else:
            self.cerrar()

    def mostrar_dialogo_error(self, msg): 
        ventana2 = VentanaError(self, mensage=msg)
        ventana2.ShowModal()
        ventana2.Destroy()

    def cerrar(self, event=None):
        self.Destroy()



if __name__ == "__main__":
    app1 = App(0)
    app1.MainLoop()

I modified the names of classes and methods and some other things to follow as much as possible the style conventions of PEP-8 , there are other tweaks such as the use of super to call the initiator of the parent class or the use of sizers in the error dialog.

    
answered by 08.07.2018 / 00:49
source