Foros del Web » Programando para Internet » Python »

problemita con wx.EVT_PAINT

Estas en el tema de problemita con wx.EVT_PAINT en el foro de Python en Foros del Web. wenas: les cuento que llevo algo asi como una semana introduciéndome en python, de a poco le voy agarrando el ritmo al lenguaje en conjunto ...
  #1 (permalink)  
Antiguo 14/01/2010, 12:42
 
Fecha de Ingreso: enero-2010
Mensajes: 21
Antigüedad: 14 años, 3 meses
Puntos: 0
problemita con wx.EVT_PAINT

wenas:
les cuento que llevo algo asi como una semana introduciéndome en python, de a poco le voy agarrando el ritmo al lenguaje en conjunto con wxPython lo cual es totalmente nuevo para mi

ahora el problema que me trae aquí seria el siguiente
tengo que dibujar en pantalla una matriz o grilla pero definiendo su dimencion
se me ocurrio resolverlo con un menu, y a cada evento asignarle una ID que concuerde con la dimencion de la matriz
el problema aparece una vez que se agranda o reduce la ventana y el dibujo desaparece ya que el wx.EVT_PAINT(self, self.dibuja) cuando se ejecuta lo hace con una ID diferente y finalmente no hace lo que debiera hacer

haber si alguien se le ocurre algo, o un metodo distinto

Código Python:
Ver original
  1. import wx
  2.  
  3. ID_ABOUT=101
  4. ID_OPEN=102
  5. ID_BUTTON1=110
  6. ID_RESET=222
  7. ID_UP=111
  8. ID_DOWN=112
  9. ID_LEFT=113
  10. ID_RIGHT=114
  11. ID_START=103
  12. ID_EXIT=999
  13. ID_GRILLA2=2
  14. ID_GRILLA3=3
  15. ID_GRILLA4=4
  16. ID_GRILLA5=5
  17. ID_GRILLA6=6
  18. ID_GRILLA7=7
  19.  
  20. class MyFrame(wx.Frame):
  21.     def __init__(self, parent, mytitle, mysize):
  22.         wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=(800,600))
  23.        
  24.         self.SetBackgroundColour('light grey')
  25.         self.initialize()
  26.        
  27.     def OnAbout(self,e):
  28.         d= wx.MessageDialog( self, " A sample editor \n"
  29.                             " in wxPython","About Sample Editor", wx.OK)                
  30.         d.ShowModal()
  31.         d.Destroy()
  32.        
  33.     def OnExit(self,e):
  34.         self.Close(True)  
  35.        
  36.        
  37.     def OnOpen(self,e):
  38.         """ Open a file"""
  39.         dlg = wx.FileDialog(self, "Choose a file", self.dirname, "", "*.*", wx.OPEN)
  40.         if dlg.ShowModal() == wx.ID_OK:
  41.             self.filename=dlg.GetFilename()
  42.             self.dirname=dlg.GetDirectory()
  43.             f=open(os.path.join(self.dirname, self.filename),'r')
  44.             self.control.SetValue(f.read())
  45.             f.close()
  46.         dlg.Destroy()
  47.        
  48.        
  49.     def dibuja(self, event):
  50.         z = event.GetId()
  51.         print z
  52.         if z > 0:
  53.             dc = wx.PaintDC(self)
  54.             dc.SetPen(wx.Pen('black', 4))
  55.             dc.SetBrush(wx.WHITE_BRUSH)
  56.             x = 400
  57.             if z > 4:
  58.                 hw=80
  59.                 f=z*hw+400
  60.                 k=z*hw+50
  61.             elif z > 5:
  62.                 hw=60
  63.                 f=z*hw+400
  64.                 k=z*hw+50
  65.             else:
  66.                 hw=100
  67.                 f=z*hw+400
  68.                 k=z*hw+50
  69.             while x < f: #maximo de col
  70.                 y = 50 #pos fila
  71.                 while y < k: #max fila
  72.                     dc.DrawRectangle(x, y, hw, hw)
  73.                     y = y+hw
  74.                 x=x+hw
  75.            
  76.             wx.EVT_PAINT(self, self.dibuja) # bind the frame to the paint event    
  77.  
  78.        
  79.     def initialize(self):
  80.         grilla = wx.GridBagSizer()
  81.         self.CreateStatusBar()
  82.        
  83.         filemenu= wx.Menu()
  84.         filemenu1= wx.Menu()
  85.         filemenu.Append(ID_OPEN, "&Open"," Open a file to edit")
  86.         filemenu.AppendSeparator()
  87.         filemenu.Append(ID_ABOUT, "&About"," Information about this program")
  88.         filemenu.AppendSeparator()
  89.         filemenu.Append(ID_EXIT,"E&xit"," Terminate the program")
  90.         filemenu1.Append(ID_GRILLA2, "2x2", "Crear grilla 2x2" ,wx.ITEM_RADIO)
  91.         filemenu1.Append(ID_GRILLA3, "3x3", "Crear grilla 3x3" ,wx.ITEM_RADIO)
  92.         filemenu1.Append(ID_GRILLA4, "4x4", "Crear grilla 4x4" ,wx.ITEM_RADIO)
  93.         filemenu1.Append(ID_GRILLA5, "5x5", "Crear grilla 5x5" ,wx.ITEM_RADIO)
  94.         filemenu1.Append(ID_GRILLA6, "6x6", "Crear grilla 6x6" ,wx.ITEM_RADIO)
  95.         filemenu1.Append(ID_GRILLA7, "7x7", "Crear grilla 7x7" ,wx.ITEM_RADIO)
  96.         # Creating the menubar.
  97.         menuBar = wx.MenuBar()
  98.         menuBar.Append(filemenu,"&File")
  99.         menuBar.Append(filemenu1,"Grilla")
  100.         self.SetMenuBar(menuBar)  .
  101.         wx.EVT_MENU(self, ID_ABOUT, self.OnAbout)
  102.         wx.EVT_MENU(self, ID_EXIT, self.OnExit)
  103.         wx.EVT_MENU(self, ID_OPEN, self.OnOpen)
  104.         wx.EVT_MENU(self, ID_GRILLA2, self.dibuja)
  105.         wx.EVT_MENU(self, ID_GRILLA3, self.dibuja)
  106.         wx.EVT_MENU(self, ID_GRILLA4, self.dibuja)
  107.         wx.EVT_MENU(self, ID_GRILLA5, self.dibuja)
  108.         wx.EVT_MENU(self, ID_GRILLA6, self.dibuja)
  109.         wx.EVT_MENU(self, ID_GRILLA7, self.dibuja)
  110.        
  111.  
  112.         self.SetSizeHints(1024, 720)
  113.         self.Show(True)
  114.  
  115.  
  116. app = wx.App()
  117. mytitle = "Tests"
  118. width = 640
  119. height = 480
  120. MyFrame(None, mytitle, (width, height)).Show()
  121. app.MainLoop()

de antemano
gracias
  #2 (permalink)  
Antiguo 14/01/2010, 17:47
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
Respuesta: problemita con wx.EVT_PAINT

Primero que nada, Bienvenido!!!

Ahora pasamos a la parte del código
Código Python:
Ver original
  1. import wx
  2.  
  3. ID_GRILLA2 = 2
  4. ID_GRILLA3 = 3
  5. ID_GRILLA4 = 4
  6. ID_GRILLA5 = 5
  7. ID_GRILLA6 = 6
  8. ID_GRILLA7 = 7
  9.  
  10. class MyFrame(wx.Frame):
  11.     def __init__(self, *args, **kargs):
  12.         wx.Frame.__init__(self, *args, **kargs)
  13.  
  14.         #Creamos un Panel dibujable y el MenuBar
  15.         self.Panel = DrawPanel(self)
  16.         menuBar = wx.MenuBar()
  17.  
  18.         #Añadimos menus
  19.         filemenu = wx.Menu()
  20.         grillamenu = wx.Menu()
  21.  
  22.         #Añadimos elementos a esos menus
  23.         filemenu.Append(wx.ID_EXIT, "&Close", "Close the program")
  24.         for i in range(2, 7 + 1):
  25.             grillamenu.Append(i, "%dx%d"%(i, i), "Crear grilla %dx%d" % (i, i), wx.ITEM_RADIO)
  26.  
  27.         #Añadimos los menus a la barra de menus
  28.         menuBar.Append(filemenu, "&File")
  29.         menuBar.Append(grillamenu, "&Grill")
  30.  
  31.         #Por ultimo ajustamos la barra de menu
  32.         self.SetMenuBar(menuBar)
  33.  
  34.         #Linkeamos los eventos a funciones con su respectiva ID
  35.         self.Bind(wx.EVT_MENU, self.OnExit, id=wx.ID_EXIT)
  36.         for i in range(2, 7 +1):
  37.             self.Bind(wx.EVT_MENU, self.SET_ID, id=i)
  38.  
  39.     def SET_ID(self, event):
  40.         #Ajustamos el numero de cuadritos a dibujar
  41.         self.Panel.n = event.GetId()
  42.         self.Panel.Refresh() #Importante redibuja todo el frame
  43.    
  44.     def OnExit(self, event):
  45.         self.Close(True)
  46.  
  47. class DrawPanel(wx.Panel):
  48.     """Draw a line to a panel."""
  49.     def __init__(self, *args, **kwargs):
  50.         wx.Panel.__init__(self, *args, **kwargs)
  51.         self.Bind(wx.EVT_PAINT, self.OnPaint)
  52.         #Por defecto son 2
  53.         self.n = 2
  54.  
  55.     def OnPaint(self, event):
  56.         dc = wx.PaintDC(self)
  57.         #dc.Clear() #Prueba
  58.         dc.SetPen(wx.Pen("BLACK", 4))
  59.         n = self.n #Acortamos el nombre
  60.         z = 30 #Tamaño de los cuadritos
  61.         for i in range(n):
  62.             for j in range(n):
  63.                 dc.DrawRectangle(i * z, j * z, z, z)
  64.  
  65. app = wx.PySimpleApp(False)
  66. frame = MyFrame(None, title="Draw on Panel!!!")
  67. frame.SetSizeHints(640, 480)
  68. frame.Show(True)
  69. app.MainLoop()

No dudes en preguntar de nuevo si algo no esta claro.
  #3 (permalink)  
Antiguo 15/01/2010, 06:47
 
Fecha de Ingreso: enero-2010
Mensajes: 21
Antigüedad: 14 años, 3 meses
Puntos: 0
Respuesta: problemita con wx.EVT_PAINT

muchas gracias
esto me sirve bastante para poder continuar con el proyecto

nuevamente se agradece
  #4 (permalink)  
Antiguo 15/01/2010, 12:29
 
Fecha de Ingreso: enero-2010
Mensajes: 21
Antigüedad: 14 años, 3 meses
Puntos: 0
Respuesta: problemita con wx.EVT_PAINT

es factible acomodar el DrawPanle a un costado del frame (ocupar unos 3/4 de el) para poner en el espacio restante unas box o grillas y ahi poner botones y TextCtrl
ya que trate de hacerlo en el mismo panel, pero se satura de inmediato el programa
  #5 (permalink)  
Antiguo 15/01/2010, 12:42
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
Respuesta: problemita con wx.EVT_PAINT

Claro que si con un simple sizer:
Código Python:
Ver original
  1. #coding: utf-8
  2. import wx
  3.  
  4. ID_GRILLA2 = 2
  5. ID_GRILLA3 = 3
  6. ID_GRILLA4 = 4
  7. ID_GRILLA5 = 5
  8. ID_GRILLA6 = 6
  9. ID_GRILLA7 = 7
  10.  
  11. class MyFrame(wx.Frame):
  12.     def __init__(self, *args, **kargs):
  13.         wx.Frame.__init__(self, *args, **kargs)
  14.  
  15.         #Creamos un Panel dibujable y el MenuBar
  16.         self.Panel = DrawPanel(self)
  17.         self.ButtonExample = wx.Button(self, -1, "Botton Example")
  18.         menuBar = wx.MenuBar()
  19.         sizer = wx.BoxSizer(wx.VERTICAL)
  20.         sizer.Add(self.Panel, 1, wx.EXPAND, 0)
  21.         sizer.Add(self.ButtonExample, 0, 0, 0)
  22.  
  23.         #Añadimos menus
  24.         filemenu = wx.Menu()
  25.         grillamenu = wx.Menu()
  26.  
  27.         #Añadimos elementos a esos menus
  28.         filemenu.Append(wx.ID_EXIT, "&Close", "Close the program")
  29.         for i in range(2, 7 + 1):
  30.             grillamenu.Append(i, "%dx%d"%(i, i), "Crear grilla %dx%d" % (i, i), wx.ITEM_RADIO)
  31.  
  32.         #Añadimos los menus a la barra de menus
  33.         menuBar.Append(filemenu, "&File")
  34.         menuBar.Append(grillamenu, "&Grill")
  35.  
  36.         #Por ultimo ajustamos la barra de menu
  37.         self.SetMenuBar(menuBar)
  38.  
  39.         #Ajutes del sizer
  40.         self.SetSizer(sizer)
  41.         self.Layout()
  42.  
  43.         #Linkeamos los eventos a funciones con su respectiva ID
  44.         self.Bind(wx.EVT_MENU, self.OnExit, id=wx.ID_EXIT)
  45.         for i in range(2, 7 +1):
  46.             self.Bind(wx.EVT_MENU, self.SET_ID, id=i)
  47.  
  48.     def SET_ID(self, event):
  49.         #Ajustamos el numero de cuadritos a dibujar
  50.         self.Panel.n = event.GetId()
  51.         self.Panel.Refresh() #Importante redibuja todo el frame
  52.    
  53.     def OnExit(self, event):
  54.         self.Close(True)
  55.  
  56. class DrawPanel(wx.Panel):
  57.     """Draw a line to a panel."""
  58.     def __init__(self, *args, **kwargs):
  59.         wx.Panel.__init__(self, *args, **kwargs)
  60.         self.Bind(wx.EVT_PAINT, self.OnPaint)
  61.         #Por defecto son 2
  62.         self.n = 2
  63.  
  64.     def OnPaint(self, event):
  65.         dc = wx.PaintDC(self)
  66.         #dc.Clear() #Prueba
  67.         dc.SetPen(wx.Pen("BLACK", 4))
  68.         n = self.n #Acortamos el nombre
  69.         z = 30 #Tamaño de los cuadritos
  70.         for i in range(n):
  71.             for j in range(n):
  72.                 dc.DrawRectangle(i * z, j * z, z, z)
  73.  
  74. app = wx.PySimpleApp(False)
  75. frame = MyFrame(None, title="Draw on Panel!!!")
  76. frame.SetSizeHints(640, 480)
  77. frame.Show(True)
  78. app.MainLoop()
  #6 (permalink)  
Antiguo 15/01/2010, 13:28
 
Fecha de Ingreso: enero-2010
Mensajes: 21
Antigüedad: 14 años, 3 meses
Puntos: 0
Respuesta: problemita con wx.EVT_PAINT

vale grax, es como lo que termine haciendo al final
con el sizer, deje el drawpanel a la derecha, y a la izquierda le puse un GridBagSizer
y con ese pude ordenar los botones de manera mas facil

grax denuevo, te pasaste
  #7 (permalink)  
Antiguo 18/01/2010, 06:57
 
Fecha de Ingreso: enero-2010
Mensajes: 21
Antigüedad: 14 años, 3 meses
Puntos: 0
Respuesta: problemita con wx.EVT_PAINT

en python hay algo que funcione como un formulario en los dialogs para llevar varios parámetros???
con la idea de setear el tamaño de la matriz pero que sea de NxM
ademas que los botones pueda interactuar con el panel tambien
para que se entienda mejor, aqui va mi codigo

Código Python:
Ver original
  1. import wx
  2. import  cStringIO
  3. from Main import opj
  4.  
  5. ID_GRILLA2 = 2
  6. ID_GRILLA3 = 3
  7. ID_GRILLA4 = 4
  8. ID_GRILLA5 = 5
  9. ID_GRILLA6 = 6
  10. ID_GRILLA7 = 7
  11. ID_UP=111
  12. ID_DOWN=112
  13. ID_LEFT=113
  14. ID_RIGHT=114
  15. ID_START=103
  16. ID_EXIT=999
  17. ID_RESET=222
  18.  
  19. class MyFrame(wx.Frame):
  20.     arreglo = []
  21.     def __init__(self, *args, **kargs):
  22.         wx.Frame.__init__(self, *args, **kargs)
  23.        
  24.         #topsizer = wx.GridSizer(1, 2)
  25.         topsizer = wx.BoxSizer( wx.HORIZONTAL )
  26.        
  27.         #menusizer = wx.GridSizer(4, 1)
  28.         menusizer = wx.BoxSizer( wx.VERTICAL )
  29.        
  30.         asdf = wx.GridBagSizer()
  31.         contentsizer = wx.BoxSizer( wx.VERTICAL )
  32.         self.CreateStatusBar()
  33.        
  34.         #Creamos un Panel dibujable y el MenuBar
  35.         self.Panel = DrawPanel(self)
  36.         menuBar = wx.MenuBar()
  37.        
  38.  
  39.  
  40.  
  41.        
  42.         self.entrada = wx.TextCtrl(self,-1,value=u"",size=(350,-1))
  43.        
  44.         imageFile = "images/arriba.png"
  45.         image1 = wx.Image(imageFile, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
  46.         arriba = wx.BitmapButton(self, ID_UP, bitmap=image1,size = (image1.GetWidth()+10, image1.GetHeight()+10))
  47.         arriba.Bind(wx.EVT_BUTTON, self.button1Click)
  48.        
  49.         imageFile = "images/atras.png"
  50.         image1 = wx.Image(imageFile, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
  51.         atras = wx.BitmapButton(self, ID_DOWN, bitmap=image1,size = (image1.GetWidth()+10, image1.GetHeight()+10))
  52.         atras.Bind(wx.EVT_BUTTON, self.button1Click)
  53.        
  54.         imageFile = "images/izquierda.png"
  55.         image1 = wx.Image(imageFile, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
  56.         izquierda = wx.BitmapButton(self, ID_LEFT, bitmap=image1,size = (image1.GetWidth()+10, image1.GetHeight()+10))
  57.        
  58.         imageFile = "images/derecha.png"
  59.         image1 = wx.Image(imageFile, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
  60.         derecha = wx.BitmapButton(self, ID_RIGHT, bitmap=image1,size = (image1.GetWidth()+10, image1.GetHeight()+10))
  61.        
  62.         imageFile = "images/start.png"
  63.         image1 = wx.Image(imageFile, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
  64.         start = wx.BitmapButton(self, ID_START, bitmap=image1,size = (image1.GetWidth()+10, image1.GetHeight()+10))
  65.        
  66.         imageFile = "images/exit.png"
  67.         image1 = wx.Image(imageFile, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
  68.         reset = wx.BitmapButton(self, ID_RESET, bitmap=image1,size = (image1.GetWidth()-3, image1.GetHeight()-3))
  69.        
  70.         arriba.Bind(wx.EVT_BUTTON, self.button1Click)
  71.         atras.Bind(wx.EVT_BUTTON, self.button1Click)
  72.         derecha.Bind(wx.EVT_BUTTON, self.button1Click)
  73.         izquierda.Bind(wx.EVT_BUTTON, self.button1Click)
  74.         reset.Bind(wx.EVT_BUTTON, self.OnReplace)
  75.        
  76.        
  77.         contentsizer.Add(self.Panel,1,wx.EXPAND)
  78.         asdf.Add(self.entrada, (0,0),(1,10))
  79.         asdf.Add(arriba, (3,2))
  80.         asdf.Add(atras, (5,2))
  81.         asdf.Add(derecha, (4,3))
  82.         asdf.Add(izquierda, (4,1))
  83.         asdf.Add(start, (7,1))
  84.         asdf.Add(reset, (7,3))
  85.         menusizer.Add(asdf, 0)
  86.        
  87.         topsizer.Add(menusizer, 0)
  88.         topsizer.Add(contentsizer, 1, wx.EXPAND)
  89.        
  90.         self.SetSizer(topsizer)
  91.        
  92.        
  93.      
  94.        
  95.         #Aniadimos menus
  96.         filemenu = wx.Menu()
  97.         grillamenu = wx.Menu()
  98.  
  99.         #Aniadimos elementos a esos menus
  100.         filemenu.Append(wx.ID_EXIT, "&Close", "Close the program")
  101.         for i in range(2, 7 + 1):
  102.             grillamenu.Append(i, "%dx%d"%(i, i), "Crear grilla %dx%d" % (i, i), wx.ITEM_RADIO)
  103.  
  104.         #Aniadimos los menus a la barra de menus
  105.         menuBar.Append(filemenu, "&File")
  106.         menuBar.Append(grillamenu, "&Grill")
  107.  
  108.         #Por ultimo ajustamos la barra de menu
  109.         self.SetMenuBar(menuBar)
  110.        
  111.  
  112.         #Linkeamos los eventos a funciones con su respectiva ID
  113.         self.Bind(wx.EVT_MENU, self.OnExit, id=wx.ID_EXIT)
  114.         for i in range(2, 7 +1):
  115.             self.Bind(wx.EVT_MENU, self.SET_ID, id=i)
  116.        
  117.        
  118.     def button1Click(self,event):
  119.         if event.GetId() == 111:
  120.             buff = "/\ "
  121.             buffT = "adelante"
  122.         if event.GetId() == 113:
  123.             buff = "< "
  124.             buffT = "izquierda"
  125.         if event.GetId() == 114:
  126.             buff = "> "
  127.             buffT = "derecha"
  128.         if event.GetId() == 112:
  129.             buff = "\/ "
  130.             buffT = "atras"
  131.         self.arreglo.append(buffT)
  132.         print self.arreglo
  133.         self.entrada.WriteText(buff+",")    
  134.        
  135.     def OnReplace(self, evt):
  136.         #self.tc.Replace(5, 9, "IS A")
  137.         self.entrada.Remove(0,100)
  138.         self.arreglo = []
  139.    
  140.  
  141.     def SET_ID(self, event):
  142.         #Ajustamos el numero de cuadritos a dibujar
  143.         self.Panel.n = event.GetId()
  144.         self.Panel.Refresh() #Importante redibuja todo el frame
  145.    
  146.     def OnExit(self, event):
  147.         self.Close(True)
  148.        
  149.    
  150.  
  151. class DrawPanel(wx.Panel):
  152.     """Draw a line to a panel."""
  153.     def __init__(self, *args, **kwargs):
  154.         wx.Panel.__init__(self, *args, **kwargs)
  155.         self.Bind(wx.EVT_PAINT, self.OnPaint)
  156.  
  157.         #Por defecto son 2
  158.         self.n = 2
  159.        
  160.         data = open(opj('images/robot.jpg'), "rb").read()
  161.         stream = cStringIO.StringIO(data)
  162.    
  163.         bmp = wx.BitmapFromImage( wx.ImageFromStream( stream ))
  164.         ver=320 #centro caja 1 2x2
  165.         hor=460
  166.         wx.StaticBitmap(self, -1, bmp, (ver, hor))#, (bmp.GetWidth(), bmp.GetHeight()))}
  167.  
  168.     def OnPaint(self, event):
  169.        
  170.         dc = wx.PaintDC(self)
  171.        
  172.         #dc.Clear() #Prueba
  173.         dc.SetPen(wx.Pen("BLACK", 4))
  174.         n = self.n #Acortamos el nombre
  175.         #
  176.         x=200 #pos inicial de la col 1
  177.         y=50  #pos inicial de la fila 1
  178.         z=560/n
  179.         for i in range(n):
  180.             for j in range(n):
  181.                 dc.DrawRectangle(i * z+x, j * z+y, z, z)
  182.                
  183.        
  184.  
  185. app = wx.PySimpleApp(False)
  186. frame = MyFrame(None, title="Simulador!!!")
  187. frame.SetSizeHints(1280, 720)
  188. frame.Show(True)
  189. app.MainLoop()

la idea es mover la imagen por la matriz deacuerdo a los botones, pero no pillo como pasar los parametros de los botones al panel para mover la imagen

Última edición por IamEdo; 18/01/2010 a las 07:59
  #8 (permalink)  
Antiguo 18/01/2010, 11:14
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
Respuesta: problemita con wx.EVT_PAINT

Código Python:
Ver original
  1. class DrawPanel(wx.Panel):
  2.     def __init__(self, *args, **kwargs):
  3.         self.pos = (0, 0)
  4.         ...
  5.  
  6. def button1Click(self,event):
  7.     self.Panle.pos = (x, y) #(x, y) Dependiendo del botón presionado
  #9 (permalink)  
Antiguo 19/01/2010, 12:50
 
Fecha de Ingreso: enero-2010
Mensajes: 21
Antigüedad: 14 años, 3 meses
Puntos: 0
Respuesta: problemita con wx.EVT_PAINT

no te comprendí muy bien la idea, puedo usar un mismo botón para llamar a 2 funciones diferentes en clases diferentes????
una que me guarde el registro de movimientos y los muestre en pantalla y la otra que mueva la imagen?
:P
  #10 (permalink)  
Antiguo 19/01/2010, 13:26
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
Respuesta: problemita con wx.EVT_PAINT

Bueno la verdad es que corrí el código :p (usas imagenes y otros archivos como main.py, así que no lo pude correr)

Cita:
Iniciado por IamEdo
puedo usar un mismo botón para llamar a 2 funciones diferentes en clases diferentes????
Si, si puedes.
Código Python:
Ver original
  1. class DrawPanel(wx.Panel):
  2.     def __init__(self, *args, **kwargs):
  3.         #Constructor de DrawPanel
  4.         self.pos = (0, 0) #Posición inicial de la imagen en la matriz.
  5.         #En el método OnPaint de la clase DrawPanel dibuja la imagen de acuerdo al contenido de la variable self.pos
  6.         ...
  7.  
  8. class MyFrame(wx.Frame):
  9.     def __init__(self, *args, **kargs):
  10.         #Constructor de MyFrame
  11.         wx.Frame.__init__(self, *args, **kargs)
  12.         #Creamos un Panel dibujable
  13.         self.Panel = DrawPanel(self)
  14.         ... #Esto significa resto del código
  15.  
  16.     def button1Click(self, event):
  17.         ... #Aqui va el código para ver que botón se presiono
  18.         self.Panle.pos = (x, y) #Establecemos la nueva posición, esta posición esta en términos de la matriz.
Espero haber comprendido la idea.

**Edito: Un ejemplo mas complejo.
Código Python:
Ver original
  1. #coding: utf-8
  2. import wx
  3.  
  4. ID_GRILLA2 = 2
  5. ID_GRILLA3 = 3
  6. ID_GRILLA4 = 4
  7. ID_GRILLA5 = 5
  8. ID_GRILLA6 = 6
  9. ID_GRILLA7 = 7
  10.  
  11. ID_UP = 10
  12. ID_DOWN = 11
  13. ID_LEFT = 12
  14. ID_RIGHT = 13
  15.  
  16. class MyFrame(wx.Frame):
  17.     def __init__(self, *args, **kargs):
  18.         wx.Frame.__init__(self, *args, **kargs)
  19.  
  20.         #Creamos un Panel dibujable y el MenuBar
  21.         self.Panel = DrawPanel(self)
  22.         menuBar = wx.MenuBar()
  23.        
  24.         #Botones
  25.         l = ['UP', 'DOWN', 'RIGHT', 'LEFT']
  26.         self.buttons = []
  27.         for i, j in zip(l, range(10, 13 + 1)):
  28.             self.buttons.append(wx.Button(self, j, i))
  29.  
  30.         #El sizer
  31.         sizer = wx.BoxSizer(wx.VERTICAL)
  32.         sizer.Add(self.Panel, 1, wx.EXPAND, 0)
  33.         for i in self.buttons:
  34.             sizer.Add(i, 0, 0, 0)
  35.  
  36.         #Añadimos menus
  37.         filemenu = wx.Menu()
  38.         grillamenu = wx.Menu()
  39.  
  40.         #Añadimos elementos a esos menus
  41.         filemenu.Append(wx.ID_EXIT, "&Close", "Close the program")
  42.         for i in range(2, 7 + 1):
  43.             grillamenu.Append(i, "%dx%d"%(i, i), "Crear grilla %dx%d" % (i, i), wx.ITEM_RADIO)
  44.  
  45.         #Añadimos los menus a la barra de menus
  46.         menuBar.Append(filemenu, "&File")
  47.         menuBar.Append(grillamenu, "&Grill")
  48.  
  49.         #Por ultimo ajustamos la barra de menu
  50.         self.SetMenuBar(menuBar)
  51.  
  52.         #Ajutes del sizer
  53.         self.SetSizer(sizer)
  54.         self.Layout()
  55.  
  56.         #Linkeamos los eventos a funciones con su respectiva ID
  57.         self.Bind(wx.EVT_MENU, self.OnExit, id=wx.ID_EXIT)
  58.         for i in range(2, 7 +1):
  59.             self.Bind(wx.EVT_MENU, self.SET_ID, id=i)
  60.         for button in self.buttons:
  61.             button.Bind(wx.EVT_BUTTON, self.MOVE_IMAGE)
  62.  
  63.     def MOVE_IMAGE(self, event):
  64.         id = event.GetId()
  65.         n = self.Panel.n
  66.         pos = self.Panel.pos
  67.         #10 -> UP
  68.         #11 -> DOWN
  69.         #12 -> RIGHT
  70.         #13 -> LEFT
  71.         if id == 10 and pos[1] > 0:
  72.             pos[1] -= 1
  73.         elif id == 11 and pos[1] < n-1:
  74.             pos[1] += 1
  75.         elif id == 12 and pos[0] < n-1:
  76.             pos[0] += 1
  77.         elif id == 13 and pos[0] > 0:
  78.             pos[0] -= 1
  79.         self.Panel.Refresh() #Importante redibuja todo el frame
  80.  
  81.     def SET_ID(self, event):
  82.         #Ajustamos el numero de cuadritos a dibujar
  83.         self.Panel.n = event.GetId()
  84.         self.Panel.Refresh() #Importante redibuja todo el frame
  85.    
  86.     def OnExit(self, event):
  87.         self.Close(True)
  88.  
  89. class DrawPanel(wx.Panel):
  90.     """Draw a line to a panel."""
  91.     def __init__(self, *args, **kwargs):
  92.         wx.Panel.__init__(self, *args, **kwargs)
  93.         self.Bind(wx.EVT_PAINT, self.OnPaint)
  94.         #Por defecto son 2
  95.         self.n = 2
  96.         self.pos = [0, 0]
  97.  
  98.     def OnPaint(self, event):
  99.         dc = wx.PaintDC(self)
  100.         #dc.Clear() #Prueba
  101.         dc.SetPen(wx.Pen("BLACK", 4))
  102.         n = self.n #Acortamos el nombre
  103.         z = 30 #Tamaño de los cuadritos
  104.         for i in range(n):
  105.             for j in range(n):
  106.                 dc.DrawRectangle(i * z, j * z, z, z)
  107.         dc.SetPen(wx.Pen("GREEN", 4))
  108.         dc.DrawRectangle(self.pos[0] * z, self.pos[1] * z, z, z)
  109.  
  110. app = wx.PySimpleApp(False)
  111. frame = MyFrame(None, title="Draw on Panel!!!")
  112. frame.SetSizeHints(640, 480)
  113. frame.Show(True)
  114. app.MainLoop()

Última edición por razpeitia; 19/01/2010 a las 14:01
  #11 (permalink)  
Antiguo 19/01/2010, 14:06
 
Fecha de Ingreso: enero-2010
Mensajes: 21
Antigüedad: 14 años, 3 meses
Puntos: 0
Respuesta: problemita con wx.EVT_PAINT

wenisima
con eso me quedo mas claro y me funciono
ahora es cosa de que interprete los movimientos con las cordenadas y voi casi terminando

grax nuevamente ;)
  #12 (permalink)  
Antiguo 22/01/2010, 08:09
 
Fecha de Ingreso: enero-2010
Mensajes: 21
Antigüedad: 14 años, 3 meses
Puntos: 0
Respuesta: problemita con wx.EVT_PAINT

Nueva consulta
se supone que tomo un arreglo con las instrucciones de movimiento, luego las interpreto y con eso comienzo a mover la imagen (asunto que todavía no tengo bien definido)
para esto voy a usar un while que recorra el arreglo, le incorporo el algoritmo para moverme en la matriz y mostrar la imagen

entonces haciendo pruebas básicas para ver si era factible este método me pille otro problema que no logro descifrar
Código Python:
Ver original
  1. def start(self, event):
  2.         x=0
  3.         p1=340
  4.         p2=470
  5.         while x < 6:
  6.             print x
  7.             p1=p1-30
  8.             p2=p2-30
  9.             jpg = wx.Image(opj('images/robot.jpg'), wx.BITMAP_TYPE_JPEG).ConvertToBitmap()
  10.             wx.StaticBitmap(self, -1, jpg, (p1,p2), (jpg.GetWidth(), jpg.GetHeight()))
  11.             x=x+1
  12.             time.sleep(5)
el problema es que el time sleep se ejecuta las 5 veces pero la imagen aparece en la pantalla después de que ya se ejecuto el while por completo y me muestra las 6 imágenes al mismo tiempo


y como caso aparte, como se podría hacer para dar una posicion nueva a la imagen pero que la imagen anterior no quede en la pantalla, la idea es que parezca que se esta moviendo, a no ser que exista un método para moverla?
  #13 (permalink)  
Antiguo 22/01/2010, 10:34
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
Respuesta: problemita con wx.EVT_PAINT

Como es de pensarlo, el evento OnPaint no se ejecutara hasta que el evento start termine.
Es por eso que no pinta nada hasta que termine.

El proceso para simular movimiento, en un programa sigue mas o menos la siguiente estructura:
-- Recibo entradas (ejem. presionar un boton)
-- Proceso entradas (en base al botón presionado, ejecuto alguna(s) operacion(es). Ejem cambio o no la posicion de la imagen)
-- Borrado de pantalla
-- Dibujar (Ojo Panel.Refresh(), hace los 2 en ese orden)

Es importante el orden, también es importante no mezclar los procesos.
  #14 (permalink)  
Antiguo 22/01/2010, 13:28
 
Fecha de Ingreso: enero-2010
Mensajes: 21
Antigüedad: 14 años, 3 meses
Puntos: 0
Respuesta: problemita con wx.EVT_PAINT

vale, ahora entiendo por que la falla con las imagenes
voy a testear con las librerías de pygame que estan diseñadas para esos propositos
haber si sale algo bueno de eso

grax nuevamente
  #15 (permalink)  
Antiguo 03/02/2010, 07:57
 
Fecha de Ingreso: enero-2010
Mensajes: 21
Antigüedad: 14 años, 3 meses
Puntos: 0
Respuesta: problemita con wx.EVT_PAINT

nueva duda
como podría recorrer un arreglo, el cual le asigna la posicion a la imagen y que el OnPaint se actualice con por cada elemento del arreglo

a modo de detalle, utilice el metodo DrawBitmap para mostrar la imagen a modo de dibujo por lo que al cambiar la posicion de la imagen la anterior ya no esta

ya vi que con un ciclo no sirve por ke el OnPaint no se ejecuta hasta que termine el ciclo, por lo ke solo se ve la imagen en la ultima posicion
y con una funcion recursiva pasa lo mismo
alguna idea???
  #16 (permalink)  
Antiguo 03/02/2010, 12:04
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
Respuesta: problemita con wx.EVT_PAINT

Leyendo un poquito la documentación, me tope con el método Update en wx.Panel
Código Python:
Ver original
  1. #coding: utf-8
  2. import wx
  3. from time import sleep
  4.  
  5. ID_GRILLA2 = 2
  6. ID_GRILLA3 = 3
  7. ID_GRILLA4 = 4
  8. ID_GRILLA5 = 5
  9. ID_GRILLA6 = 6
  10. ID_GRILLA7 = 7
  11.  
  12. ID_UP = 10
  13. ID_DOWN = 11
  14. ID_LEFT = 12
  15. ID_RIGHT = 13
  16. ID_START = 14
  17.  
  18. class MyFrame(wx.Frame):
  19.     def __init__(self, *args, **kargs):
  20.         wx.Frame.__init__(self, *args, **kargs)
  21.  
  22.         #Creamos un Panel dibujable y el MenuBar
  23.         self.Panel = DrawPanel(self)
  24.         menuBar = wx.MenuBar()
  25.        
  26.         #Boton para empezar
  27.         self.StartButton = wx.Button(self, label="start")
  28.  
  29.         #Instrucciones a seguir:
  30.         self.inst = [11, 13, 10]
  31.  
  32.         #El sizer
  33.         sizer = wx.BoxSizer(wx.VERTICAL)
  34.         sizer.Add(self.Panel, 1, wx.EXPAND, 0)
  35.         sizer.Add(self.StartButton)
  36.  
  37.         #Añadimos menus
  38.         filemenu = wx.Menu()
  39.         grillamenu = wx.Menu()
  40.  
  41.         #Añadimos elementos a esos menus
  42.         filemenu.Append(wx.ID_EXIT, "&Close", "Close the program")
  43.         for i in range(2, 7 + 1):
  44.             grillamenu.Append(i, "%dx%d"%(i, i), "Crear grilla %dx%d" % (i, i), wx.ITEM_RADIO)
  45.  
  46.         #Añadimos los menus a la barra de menus
  47.         menuBar.Append(filemenu, "&File")
  48.         menuBar.Append(grillamenu, "&Grill")
  49.  
  50.         #Por ultimo ajustamos la barra de menu
  51.         self.SetMenuBar(menuBar)
  52.  
  53.         #Ajutes del sizer
  54.         self.SetSizer(sizer)
  55.         self.Layout()
  56.  
  57.         #Linkeamos los eventos a funciones con su respectiva ID
  58.         self.Bind(wx.EVT_MENU, self.OnExit, id=wx.ID_EXIT)
  59.         for i in range(2, 7 +1):
  60.             self.Bind(wx.EVT_MENU, self.SET_ID, id=i)
  61.         #Boton de inicio
  62.         self.StartButton.Bind(wx.EVT_BUTTON, self.MOVE_IMAGE)
  63.  
  64.     def MOVE_IMAGE(self, event):
  65.         print "Move Image, Click in button start"
  66.         n = self.Panel.n
  67.         pos = self.Panel.pos
  68.         #10 -> UP
  69.         #11 -> DOWN
  70.         #12 -> LEFT
  71.         #13 -> RIGHT
  72.         for id in self.inst:
  73.             if id == 10 and pos[1] > 0:
  74.                 pos[1] -= 1
  75.             elif id == 11 and pos[1] < n-1:
  76.                 pos[1] += 1
  77.             elif id == 13 and pos[0] < n-1:
  78.                 pos[0] += 1
  79.             elif id == 12 and pos[0] > 0:
  80.                 pos[0] -= 1
  81.             sleep(1)
  82.             self.Panel.Refresh() #Con esto llamamos al evento OnPaint al terminar este evento
  83.             self.Panel.Update()
  84.  
  85.     def SET_ID(self, event):
  86.         print "SET_ID"
  87.         #Ajustamos el numero de cuadritos a dibujar
  88.         self.Panel.n = event.GetId()
  89.         self.Panel.Refresh() #Importante redibuja todo el frame
  90.    
  91.     def OnExit(self, event):
  92.         self.Close(True)
  93.  
  94. class DrawPanel(wx.Panel):
  95.     """Draw a line to a panel."""
  96.     def __init__(self, *args, **kwargs):
  97.         wx.Panel.__init__(self, *args, **kwargs)
  98.         self.Bind(wx.EVT_PAINT, self.OnPaint)
  99.         #Por defecto son 2
  100.         self.n = 2
  101.         self.pos = [0, 0]
  102.  
  103.     def OnPaint(self, event):
  104.         print "Painting"
  105.         dc = wx.PaintDC(self)
  106.         dc.SetPen(wx.Pen("BLACK", 4))
  107.         n = self.n #Acortamos el nombre
  108.         z = 30 #Tamaño de los cuadritos
  109.         for i in range(n):
  110.             for j in range(n):
  111.                 dc.DrawRectangle(i * z, j * z, z, z)
  112.         dc.SetPen(wx.Pen("GREEN", 4))
  113.         dc.DrawRectangle(self.pos[0] * z, self.pos[1] * z, z, z)
  114.  
  115. app = wx.PySimpleApp(False)
  116. frame = MyFrame(None, title="Draw on Panel!!!")
  117. frame.SetSizeHints(640, 480)
  118. frame.Show()
  119. app.MainLoop()

Como puedes tienes un arreglo llamado inst (que contiene las instrucciones, en clase MyFrame).
  #17 (permalink)  
Antiguo 03/02/2010, 13:23
 
Fecha de Ingreso: enero-2010
Mensajes: 21
Antigüedad: 14 años, 3 meses
Puntos: 0
Respuesta: problemita con wx.EVT_PAINT

exelente , nuevamente te las mandaste
grax

Etiquetas: Ninguno
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 19:57.