Thomas Weholt wrote:
I'm trying to understand TransferDataToWindow/TransferDataFromWindow and I've looked at some of the docs in the wiki, but so far I'm not getting anywhere.
I don't found those pages. Can you send me the page?
Can somebody show me a simple example on how to use those methods to
set and get values from a window?
I normally use the following code. I don't know if you like it, but for
my usage it work well. It has the getWidgetsValue and setWidgetsValue
methods. You need only to create your class, inherit from a wx.Window
(or something over it) and from FetchValuesWx. Attached are an example
to explain the class usage.
However, nothing special, it only iterate over a dir(self) and see if the class attribute inherit from wx.Control. That's all!
(Hope that code are well-formatted. If not I'll attach the file into an email.)
<-code->
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wx, wx.stc, sys
class FetchValuesWx(object):
""" Class for fetch/set values from/to the widgets inside
"""
def __init__(self, *args, **kw):
"""
super(FetchValuesWx, self).__init__(*args, **kw)
self.lstValueFetch = list()
self.lstValueSkip = list()
#self.lstValueSkip += [wx.Notebook, ]
#List need for solve wx bug on equal operations:
# wxFontInst in [1,] raise an exception!
self._lstBugEq = [wx.Font, wx.Notebook]
def getWidgetsValue(self, positionOrString=1):
""" Return the values that the widgets has.
@arg positionOrString: How I have to get the value
for the "ControlWithItems"?
If 1 as int(position), 2 as string (selection)
@type positionOrString: int
@return : Dict with {widget_name: value, }
"""
#Create the list where will iterator on
mayBeWidgets = self.__mayBeWidget()
retDict = dict()
for w in mayBeWidgets:
attr = getattr(self, w)
if isinstance(attr, (wx.Button, wx.StaticText)):
continue
elif isinstance(attr, wx.CheckListBox):
value = [ attr.IsChecked(x) for x in xrange(attr.GetCount()) ]
elif isinstance(attr, (wx.ControlWithItems, wx.RadioBox)):
#wants position
if positionOrString == 1:
value = attr.GetSelection()
#wants string
elif positionOrString == 2:
value = attr.GetStringSelection()
else: continue
elif isinstance(attr, (wx.TextCtrl, wx.CheckBox, wx.SpinCtrl)):
value = attr.GetValue()
elif isinstance(attr, wx.stc.StyledTextCtrl):
value = attr.GetText()
elif w in self.lstValueFetch:
value = getattr(self, w)
else:
print "No value fetch for %s" % attr
continue
retDict[w] = value
return retDict
def setWidgetsValue(self, data):
"""
if not isinstance(data, dict):
print "I cannot set data with this values type: %s. Pass me a dict at %s" % (type(data), __file__)
return
mayBeWidgets = self.__mayBeWidget()
for w in mayBeWidgets:
attr = getattr(self, w)
#Fetch the value
value = data.get(w, None)
if not value: continue
if isinstance(attr, (wx.Button, wx.StaticText)):
continue
elif isinstance(attr, wx.CheckListBox):
if isinstance( value, (tuple, list) ) and len(value) == attr.GetCount():
for v in value:
if v: valueSet = True
else: valueSet = False
attr.Checked(valueSet)
else:
print ( "I cannot set value %s for the checklistbox.\n" % str(value) +
"Lengh: Value: %i, Checklistbox: %i" % (len(value), attr.GetCount()) )
elif isinstance(attr, (wx.ControlWithItems, wx.RadioBox)):
#wants position
if str(value).isdigit() and int(value) < attr.GetCount():
attr.SetSelection( int(value) )
#wants string
elif isinstance(value, basestring) and attr.FindString(value) != wx.NOT_FOUND:
attr.SetStringSelection(value)
else:
print "No values set for radioBox"
continue
elif isinstance(attr, wx.TextCtrl):
if isinstance(value, (int, float)):
value = str(value)
attr.SetValue(value)
elif isinstance(attr, wx.stc.StyledTextCtrl):
attr.SetText(value)
elif isinstance(attr, (wx.CheckBox, wx.SpinCtrl)):
value = attr.SetValue(int(value))
elif w in self.lstValueFetch:
setattr(self, w, value)
else:
print "No value set for %s" % attr
continue
def emptyWidgets(self):
""" Set a null value to all the widgets
"""
mayBeWidgets = self.__mayBeWidget()
for w in mayBeWidgets:
attr = getattr(self, w)
if isinstance(attr, wx.TextCtrl):
attr.SetValue("")
elif isinstance(attr, (wx.CheckBox, wx.RadioButton)):
attr.SetValue(0)
elif isinstance(attr, (wx.Button, wx.StaticText)):
continue
elif isinstance(attr, (wx.ControlWithItems, wx.RadioBox)):
if attr.GetCount() > 0: self.SetSelection(0)
else: continue
elif isinstance(attr, wx.stc.StyledTextCtrl):
attr.SetText("")
else:
print "No empty value for %s" % attr
continue
def __mayBeWidget(self):
"""
mayBeWidgets =
#Create the list where will iterator on
for w in dir(self):
attr = getattr(self, w)
#Bug found
bugFound = False
for bugEq in self._lstBugEq:
if isinstance(attr, bugEq):
bugFound = True
break
if bugFound: continue
if w in self.lstValueSkip or attr in self.lstValueSkip: continue
if isinstance(attr, wx.Control) or w in self.lstValueFetch:
mayBeWidgets.append(w)
return mayBeWidgets
class f1(FetchValuesWx, wx.Frame):
def __init__(self, parent):
super(f1, self).__init__(parent)
p = wx.Panel(self)
#Widgets
btGet = wx.Button(p, label="get")
btSet = wx.Button(p, label="set")
self._txt = wx.TextCtrl(p)
self._cho = wx.Choice(p, choices=("a", "b"))
self._rb = wx.RadioBox(p,choices=("a", "b"))
#Events
btGet.Bind(wx.EVT_BUTTON, self.OnGet)
btSet.Bind(wx.EVT_BUTTON, self.OnSet)
#Sizer
szBt = wx.BoxSizer(wx.HORIZONTAL)
szWidgets = wx.BoxSizer(wx.HORIZONTAL)
szAll = wx.BoxSizer(wx.VERTICAL)
szBt.AddMany((btGet, btSet))
szWidgets.AddMany((self._txt, self._cho,self._rb))
szAll.Add(szBt)
szAll.Add(szWidgets)
p.SetSizerAndFit(szAll)
self.Show()
def OnSet(self, evt):
self.setWidgetsValue({"_txt": "10", "_cho": 1})
def OnGet(self, evt):
import pprint
wx.MessageBox("Values into widgets are:\n%s" % pprint.pformat(self.getWidgetsValue()),
"Values", wx.ICON_INFORMATION)
app = wx.PySimpleApp()
f = f1(None)
app.MainLoop()