WxPython FAQ Using xml resource files

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

The idea behind xml resources is to separate the interface from the code of an application. Several GUI builders use this concept for creating interfaces. For example the famous Glade.

In our example we create a simple frame window with one button. We load resources from a file, load a panel and bind an event to a button.

#!/usr/bin/python
# xml.py
 
import  wx
import  wx.xrc  as  xrc
 
 
class Xml(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)
 
        res = xrc.XmlResource('resource.xrc')
        res.LoadPanel(self, 'MyPanel')
 
        self.Bind(wx.EVT_BUTTON, self.OnClose,  id=xrc.XRCID('CloseButton'))
        self.Center()
        self.Show(True)
 
 
    def OnClose(self, event):
        self.Close()
 
app = wx.App()
Xml(None, -1, 'xml.py')
app.MainLoop()

This is resource file resource.xrc It is a xml file, where we define our widgets and their patterns. In thid file, we use tags like

<object></object>, <item></item>

etc.

<?xml version="1.0" ?>
<resource>
  <object class="wxPanel" name="MyPanel">
   <object class="wxButton" name="CloseButton">
    <label>Close</label>
 
    <pos>15,10</pos>
   </object>
  </object>
</resource>

We use these two calls for working with widgets:

  • XRCID(resource_name) - gives us the id of a button or menu item
  • XRCCTRL(resource_name) - gives us the handlers of our widgets defined in resource file