i followed these samples [http://www.blog.pythonlibrary.org/2011/01/04/wxpython-wx-listctrl-tips-and-tricks/][1]
and by working around it i managed to make my wxlistctrl editable for every element in it and i accomplished the sort by the column with keeping track the line after the sort.
My problem is that i have two tabs in a Notebook and in the fist tab the wxlistctrl is working as i need but in the second tab the second wxlistctrl i have presents the data , is editable but the sort is not working when i click the column
import wx
import datetime,re,os,time,urllib,errno
import sys
import wx.lib.mixins.listctrl as listmix
musicdata = {
0 : ("Bad English", "The Price Of Love", "Rock"),
1 : ("DNA featuring Suzanne Vega", "Tom's Diner", "Rock"),
2 : ("George Michael", "Praying For Time", "Rock"),
3 : ("Gloria Estefan", "Here We Are", "Rock"),
4 : ("Linda Ronstadt", "Don't Know Much", "Rock"),
5 : ("Michael Bolton", "How Am I Supposed To Live Without You", "Blues"),
6 : ("Paul Young", "Oh Girl", "Rock"),
}
musicdata2 = {
0 : ("Bad English", "The Price Of Love", "Rock"),
1 : ("DNA featuring Suzanne Vega", "Tom's Diner", "Rock"),
2 : ("George Michael", "Praying For Time", "Rock"),
3 : ("Gloria Estefan", "Here We Are", "Rock"),
4 : ("Linda Ronstadt", "Don't Know Much", "Rock"),
5 : ("Michael Bolton", "How Am I Supposed To Live Without You", "Blues"),
6 : ("Paul Young", "Oh Girl", "Rock"),
}
class Friend_info(object):
def __init__(self, idd, name, photo):
# id is used to keep tracking the rows after sorting
self.id = id(self)
self.idd = idd
self.name = name
self.photo = photo
class Messages(object):
def __init__(self, fidd, message, time_sent):
# id is used to keep tracking the rows after sorting
self.id = id(self)
self.fidd = fidd
self.message = message
self.time_sent = time_sent
class EditableListCtrl(wx.ListCtrl, listmix.TextEditMixin):
''' TextEditMixin allows any column to be edited. '''
#----------------------------------------------------------------------
def __init__(self, parent, ID=wx.ID_ANY, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=0):
"""Constructor"""
wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
listmix.TextEditMixin.__init__(self)
class Example(wx.Frame,listmix.ColumnSorterMixin):
def __init__(self, *args, **kwargs):
super(Example, self).__init__(*args, **kwargs)
self.InitUI()
def InitUI(self):
#create the panel to present the contact data with columns
bSizer1 = wx.BoxSizer(wx.HORIZONTAL)
sbSizer1 = wx.StaticBoxSizer(wx.StaticBox(self,wx.ID_ANY,u'User Info'),wx.VERTICAL)
sbSizer1.SetMinSize(wx.Size(-1,400))
bSizer3 = wx.BoxSizer(wx.VERTICAL)
text3 = wx.StaticText(self, wx.ID_ANY, u'Device User Photo',wx.DefaultPosition, wx.DefaultSize,0)
text3.Wrap( -1 )
bSizer3.Add(text3, 0, wx.ALL|wx.ALIGN_CENTER , 5 )
bSizer4 = wx.BoxSizer(wx.HORIZONTAL)
#bSizer4.SetMinSize(wx.Size(100,100))
text4 = wx.StaticText(self, wx.ID_ANY, u'Name:',wx.DefaultPosition, wx.DefaultSize,0)
text4.Wrap( -1 )
bSizer4.Add(text4, 0, wx.ALL , 5 )
bSizer3.Add(bSizer4, 1, wx.ALL , 5 )
bSizer5 = wx.BoxSizer(wx.HORIZONTAL)
#bSizer5.SetMinSize(wx.Size(100,100))
text6 = wx.StaticText(self, wx.ID_ANY, u'ID:',wx.DefaultPosition, wx.DefaultSize,0)
text6.Wrap( -1 )
bSizer5.Add(text6, 0, wx.ALL , 5 )
bSizer3.Add(bSizer5, 1, wx.ALL , 5 )
bSizer6 = wx.BoxSizer(wx.HORIZONTAL)
text8 = wx.StaticText(self, wx.ID_ANY, u'User Email:',wx.DefaultPosition, wx.DefaultSize,0)
text8.Wrap( -1 )
bSizer6.Add(text8, 0, wx.ALL , 5 )
bSizer3.Add(bSizer6, 1, wx.ALL , 5 )
text10 = wx.StaticText(self, wx.ID_ANY, u'Profile Link:',wx.DefaultPosition, wx.DefaultSize,0)
text10.Wrap( -1 )
bSizer3.Add(text10, 0, wx.ALL , 5 )
sbSizer1.Add(bSizer3,1, wx.ALL , 5 )
bSizer1.Add(sbSizer1,0, wx.ALL , 5 )
notebook1 = wx.Notebook(self,wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, 0 )
self.panel1 = wx.Panel(notebook1,wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
bSizer2 = wx.BoxSizer(wx.VERTICAL)
self.list_ctrl = EditableListCtrl(self.panel1 ,size=(-1,350), style=wx.LC_REPORT|wx.BORDER_SUNKEN|wx.LC_SORT_ASCENDING)
self.list_ctrl.InsertColumn(0, 'ID', width=50)
self.list_ctrl.InsertColumn(1, 'Display Name', width=150)
self.list_ctrl.InsertColumn(2, 'Photo Profile',width=150)
#wx.EVT_LIST_ITEM_ACTIVATED ---> with Enter it shows the photos
self.list_ctrl.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.onItemSelected)
bSizer2.Add( self.list_ctrl, 0, wx.ALL|wx.EXPAND, 5 )
gSizer1 = wx.GridSizer( 0, 4, 0, 0 )
text1 = wx.StaticText(self.panel1, -1, 'Photo Profile',wx.Point(50,0),style=wx.ALIGN_CENTRE)
text1.Wrap( -1 )
gSizer1.Add( text1, 0, wx.ALL , 5 )
text2 = wx.StaticText(self.panel1, -1, 'Cover Photo', style=wx.ALIGN_CENTRE)
text2.Wrap( -1 )
gSizer1.Add( text2, 0, wx.ALL , 5 )
text11 = wx.StaticText(self.panel1, -1, '', style=wx.ALIGN_CENTRE)
text11.Wrap( -1 )
gSizer1.Add( text11, 0, wx.ALL , 5 )
btn2 = wx.Button( self.panel1, wx.ID_ANY, u"Show information", wx.DefaultPosition, wx.DefaultSize, 0 )
btn2.Bind(wx.EVT_BUTTON, self.add_line)
gSizer1.Add( btn2, 0, wx.ALL |wx.ALIGN_RIGHT, 5 )
bitmap1 = wx.StaticBitmap(self.panel1, wx.ID_ANY, wx.NullBitmap, wx.DefaultPosition, wx.Size(100,100), 0 )
bitmap1.Bind(wx.EVT_BUTTON, self.onItemSelected)
gSizer1.Add( bitmap1, 0, wx.ALL, 5 )
bitmap2 = wx.StaticBitmap(self.panel1, wx.ID_ANY, wx.NullBitmap, wx.DefaultPosition, wx.Size(100,100), 0 )
bitmap2.Bind(wx.EVT_BUTTON, self.onItemSelected)
gSizer1.Add( bitmap2, 0, wx.ALL |wx.ALIGN_RIGHT, 5 )
bSizer2.Add( gSizer1, 1, wx.EXPAND, 5 )
self.panel1.SetSizer(bSizer2)
self.panel1.Layout()
bSizer2.Fit(self.panel1)
notebook1.AddPage(self.panel1, u"Contacts Info", True )
self.panel2 = wx.Panel( notebook1, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
notebook1.AddPage( self.panel2, u"User Chat", False )
bSizer7 = wx.BoxSizer(wx.VERTICAL)
#format=wx.LIST_FORMAT_CENTRE
self.list_ctrl2 = EditableListCtrl(self.panel2 ,size=(-1,450), style=wx.LC_REPORT|wx.BORDER_SUNKEN |wx.LC_SORT_ASCENDING)
self.list_ctrl2.InsertColumn(0, 'Fid', width=150)
self.list_ctrl2.InsertColumn(1,'Message', width=250)
self.list_ctrl2.InsertColumn(2, 'Time Sent',width=150)
self.list_ctrl2.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.onItemSelected)
bSizer7.Add( self.list_ctrl2, 0, wx.ALL|wx.EXPAND, 5 )
self.panel2.SetSizer(bSizer7)
btn3 = wx.Button( self.panel2, wx.ID_ANY, u"Show information", wx.DefaultPosition, wx.DefaultSize, 0 )
btn3.Bind(wx.EVT_BUTTON, self.add_message)
bSizer7.Add(btn3, 0, wx.ALL|wx.ALIGN_RIGHT, 5 )
bSizer1.Add(notebook1, 1, wx.EXPAND |wx.ALL, 5 )
self.SetSizer( bSizer1 )
self.Layout()
self.SetSize((1000, 650))
self.SetTitle('Simple menu')
self.Move((100,100))
self.Show(True)
items = musicdata.items()
row_list =[]
self.myRowDict = {}
#print items
for key,data in items:
row_list.append(Friend_info(data[0],data[1],data[2]))
index1 = 0
for row in row_list:
self.list_ctrl.SetItemData(index1, row.id)
self.myRowDict[index1] = row
index1 += 1
items2 = musicdata2.items()
row_list2 =[]
self.myRowDict2 = {}
index2 = 0
for key,data in items2:
row_list2.append(Messages(data[0],data[1],data[2]))
for row in row_list2:
self.list_ctrl2.SetItemData(index2, row.id)
self.myRowDict2[index2] = row
index2 += 1
# button event for adding elements
def add_line(self, event):
index = 0
items = musicdata.items()
for key, data in items:
self.list_ctrl.InsertStringItem(index, data[0])
self.list_ctrl.SetStringItem(index,1, data[1])
self.list_ctrl.SetStringItem(index, 2,data[2])
self.list_ctrl.SetItemData(index, key)
index += 1
self.itemDataMap = musicdata
listmix.ColumnSorterMixin.__init__(self, 3)
self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick, self.list_ctrl)
def add_message(self, event):
index = 0
items = musicdata2.items()
for key, data in items:
self.list_ctrl2.InsertStringItem(index, data[0])
self.list_ctrl2.SetStringItem(index,1, data[1])
self.list_ctrl2.SetStringItem(index, 2,data[2])
self.list_ctrl2.SetItemData(index, key)
index += 1
self.itemDataMap = musicdata2
listmix.ColumnSorterMixin.__init__(self, 3)
self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick, self.list_ctrl2)
def GetListCtrl(self):
return self.list_ctrl2
def OnColClick(self, event):
print "column clicked"
event.Skip()
def onItemSelected(self,event):
global size
self.currentItem = event.m_itemIndex
friend_info = self.myRowDict[self.list_ctrl.GetItemData(self.currentItem)]
self.currentItem2 = event.m_itemIndex
message = self.myRowDict2[self.list_ctrl2.GetItemData(self.currentItem2)]
self.imageFile = "images/profile/%d.jpg" %int(friend_info.name)
self.bmp = wx.Image(self.imageFile,wx.BITMAP_TYPE_JPEG).ConvertToBitmap()
bitmap1 = wx.StaticBitmap(self.panel1, -1, self.bmp, (5,400), (100,100))
self.imageFile2 = "images/cover/%d.jpg" %int(friend_info.name)
#img = Image.open('images/cover/%d.jpg'%int(friend_info.name))
if os.path.exists(self.imageFile2):
#dimensions_cover = img.size
self.bmp2 = wx.Image(self.imageFile2,wx.BITMAP_TYPE_JPEG).ConvertToBitmap()
bitmap2 = wx.StaticBitmap(self.panel1, -1, self.bmp2, (200,390))
print friend_info.name
def main():
ex = wx.App()
Example(None)
ex.MainLoop()
if __name__ == '__main__':
main()
if i change
def GetListCtrl(self):
return self.list_ctrl2
to
def GetListCtrl(self):
return self.list_ctrl
it works for each one but i want to make them work simultaneously how can i do it?
Related
hey so I followed mouseVSpython tutorial on how to set an image as my background and it worked fine except the image doesn't fully expand across the frame. Maybe im missing something here but here is the code . followed by the image
class F_Main(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent=parent)
self.SetBackgroundStyle(wx.BG_STYLE_ERASE)
self.frame = parent
bSizer6 = wx.BoxSizer(wx.VERTICAL)
bSizer5 = wx.BoxSizer(wx.HORIZONTAL)
bSizer4 = wx.BoxSizer(wx.VERTICAL)
bSizer3 = wx.BoxSizer(wx.VERTICAL)
bSizer2 = wx.BoxSizer(wx.VERTICAL)
self.lbl_WS1 = wx.StaticText(self, wx.ID_ANY, u"Wafer Sort 1",
wx.DefaultPosition, wx.DefaultSize, 0)
self.lbl_WS1.Wrap(-1)
# self.lbl_WS1.SetBackgroundColour( wx.Colour( 255, 255, 0 ) )
self.lbl_WS1.SetFont(
wx.Font(wx.NORMAL_FONT.GetPointSize(), 70, 90, 92, False,
wx.EmptyString))
bSizer4.Add(self.lbl_WS1, 0, wx.ALL, 10)
self.m_filePicker1 = wx.FilePickerCtrl(self, wx.ID_ANY, wx.EmptyString,
u"Select a file", u"*.*",
wx.DefaultPosition,
wx.DefaultSize,
wx.FLP_DEFAULT_STYLE)
bSizer4.Add(self.m_filePicker1, 0, wx.ALL, 5)
self.dateBegin = wx.adv.DatePickerCtrl(self, wx.ID_ANY,
wx.DefaultDateTime,
wx.DefaultPosition,
wx.DefaultSize,
wx.adv.DP_DROPDOWN)
bSizer4.Add(self.dateBegin, 0, wx.ALL, 5)
self.timeBegin = wx.adv.TimePickerCtrl(self, wx.ID_ANY,
wx.DefaultDateTime,
wx.DefaultPosition,
wx.DefaultSize,
wx.adv.DP_DEFAULT)
bSizer4.Add(self.timeBegin, 0, wx.ALL, 5)
self.dateEnd = wx.adv.DatePickerCtrl(self, wx.ID_ANY,
wx.DefaultDateTime,
wx.DefaultPosition,
wx.DefaultSize,
wx.adv.DP_DROPDOWN)
bSizer4.Add(self.dateEnd, 0, wx.ALL, 5)
self.timeEnd = wx.adv.TimePickerCtrl(self, wx.ID_ANY,
wx.DefaultDateTime,
wx.DefaultPosition,
wx.DefaultSize, wx.adv.DP_DEFAULT)
bSizer4.Add(self.timeEnd, 0, wx.ALL, 5)
self.btnGenerate = wx.Button(self, wx.ID_ANY, u"Generate",
wx.DefaultPosition, wx.DefaultSize, 0)
bSizer4.Add(self.btnGenerate, 0, wx.ALL, 5)
self.m_checkBox1 = wx.CheckBox(self, wx.ID_ANY, u"Report WS",
wx.DefaultPosition, wx.DefaultSize, 0)
bSizer4.Add(self.m_checkBox1, 0, wx.ALL, 5)
bSizer5.Add(bSizer4, 1, wx.EXPAND, 5)
self.lbl_WS2 = wx.StaticText(self, wx.ID_ANY, u"Wafer Sort 2",
wx.DefaultPosition, wx.DefaultSize, 0)
self.lbl_WS2.Wrap(-1)
self.lbl_WS2.SetFont(
wx.Font(wx.NORMAL_FONT.GetPointSize(), 70, 90, 92, False,
wx.EmptyString))
bSizer3.Add(self.lbl_WS2, 0, wx.ALL, 10)
self.m_filePicker2 = wx.FilePickerCtrl(self, wx.ID_ANY, wx.EmptyString,
u"Select a file", u"*.*",
wx.DefaultPosition,
wx.DefaultSize,
wx.FLP_DEFAULT_STYLE)
bSizer3.Add(self.m_filePicker2, 0, wx.ALL, 5)
self.dateBeginWS2 = wx.adv.DatePickerCtrl(self, wx.ID_ANY,
wx.DefaultDateTime,
wx.DefaultPosition,
wx.DefaultSize,
wx.adv.DP_DROPDOWN)
bSizer3.Add(self.dateBeginWS2, 0, wx.ALL, 5)
self.timeBeginWS2 = wx.adv.TimePickerCtrl(self, wx.ID_ANY,
wx.DefaultDateTime,
wx.DefaultPosition,
wx.DefaultSize,
wx.adv.DP_DEFAULT)
bSizer3.Add(self.timeBeginWS2, 0, wx.ALL, 5)
self.dateEndWS2 = wx.adv.DatePickerCtrl(self, wx.ID_ANY,
wx.DefaultDateTime,
wx.DefaultPosition,
wx.DefaultSize,
wx.adv.DP_DROPDOWN)
bSizer3.Add(self.dateEndWS2, 0, wx.ALL, 5)
self.timeEndWS2 = wx.adv.TimePickerCtrl(self, wx.ID_ANY,
wx.DefaultDateTime,
wx.DefaultPosition,
wx.DefaultSize,
wx.adv.DP_DEFAULT)
bSizer3.Add(self.timeEndWS2, 0, wx.ALL, 5)
self.btnGenerateWS2 = wx.Button(self, wx.ID_ANY, u"Generate",
wx.DefaultPosition, wx.DefaultSize, 0)
bSizer3.Add(self.btnGenerateWS2, 0, wx.ALL, 5)
self.m_checkBox2 = wx.CheckBox(self, wx.ID_ANY, u"Report WS2",
wx.DefaultPosition, wx.DefaultSize, 0)
bSizer3.Add(self.m_checkBox2, 0, wx.ALL, 5)
bSizer5.Add(bSizer3, 1, wx.EXPAND, 5)
self.lbl_FT = wx.StaticText(self, wx.ID_ANY, u"Final Testing",
wx.DefaultPosition, wx.DefaultSize, 0)
self.lbl_FT.Wrap(-1)
self.lbl_FT.SetFont(
wx.Font(wx.NORMAL_FONT.GetPointSize(), 70, 90, 92, False,
wx.EmptyString))
bSizer2.Add(self.lbl_FT, 0, wx.ALL, 10)
self.m_filePicker3 = wx.FilePickerCtrl(self, wx.ID_ANY, wx.EmptyString,
u"Select a file", u"*.*",
wx.DefaultPosition,
wx.DefaultSize,
wx.FLP_DEFAULT_STYLE)
bSizer2.Add(self.m_filePicker3, 0, wx.ALL, 5)
self.dateBeginFT = wx.adv.DatePickerCtrl(self, wx.ID_ANY,
wx.DefaultDateTime,
wx.DefaultPosition,
wx.DefaultSize,
wx.adv.DP_DROPDOWN)
bSizer2.Add(self.dateBeginFT, 0, wx.ALL, 5)
self.timeBeginFT = wx.adv.TimePickerCtrl(self, wx.ID_ANY,
wx.DefaultDateTime,
wx.DefaultPosition,
wx.DefaultSize,
wx.adv.DP_DEFAULT)
bSizer2.Add(self.timeBeginFT, 0, wx.ALL, 5)
self.dateEndFT = wx.adv.DatePickerCtrl(self, wx.ID_ANY,
wx.DefaultDateTime,
wx.DefaultPosition,
wx.DefaultSize,
wx.adv.DP_DROPDOWN)
bSizer2.Add(self.dateEndFT, 0, wx.ALL, 5)
self.timeEndFT = wx.adv.TimePickerCtrl(self, wx.ID_ANY,
wx.DefaultDateTime,
wx.DefaultPosition,
wx.DefaultSize,
wx.adv.DP_DEFAULT)
bSizer2.Add(self.timeEndFT, 0, wx.ALL, 5)
self.btnGenerateFT = wx.Button(self, wx.ID_ANY, u"Generate",
wx.DefaultPosition, wx.DefaultSize, 0)
bSizer2.Add(self.btnGenerateFT, 0, wx.ALL, 5)
self.m_checkBox3 = wx.CheckBox(self, wx.ID_ANY, u"Report FT",
wx.DefaultPosition, wx.DefaultSize, 0)
bSizer2.Add(self.m_checkBox3, 0, wx.ALL, 5)
bSizer5.Add(bSizer2, 1, wx.EXPAND, 5)
bSizer6.Add(bSizer5, 1, wx.EXPAND, 5)
self.btnReport = wx.Button(self, wx.ID_ANY, u"Report",
wx.DefaultPosition, wx.Size(1000, 25), 0)
bSizer6.Add(self.btnReport, 0, wx.ALIGN_BOTTOM, 5)
self.SetSizer(bSizer6)
self.Layout()
self.Centre(wx.BOTH)
# Connect Events
self.dateBegin.Bind(wx.adv.EVT_DATE_CHANGED, self.date_Begin)
self.timeBegin.Bind(wx.adv.EVT_TIME_CHANGED, self.time_Begin)
self.dateEnd.Bind(wx.adv.EVT_DATE_CHANGED, self.date_End)
self.timeEnd.Bind(wx.adv.EVT_TIME_CHANGED, self.time_End)
self.btnGenerate.Bind(wx.EVT_BUTTON, self.clickBtn_Generate)
self.btnGenerateWS2.Bind(wx.EVT_BUTTON, self.clickBtn_GenerateWS2)
self.btnGenerateFT.Bind(wx.EVT_BUTTON, self.clickBtn_GenerateFT)
self.m_filePicker1.Bind(wx.EVT_FILEPICKER_CHANGED, self.get_Path)
self.btnReport.Bind(wx.EVT_BUTTON, self.clickBtn_Report1)
self.dateBeginWS2.Bind(wx.adv.EVT_DATE_CHANGED, self.date_BeginWS2)
self.timeBeginWS2.Bind(wx.adv.EVT_TIME_CHANGED, self.time_BeginWS2)
self.dateEndWS2.Bind(wx.adv.EVT_DATE_CHANGED, self.date_EndWS2)
self.timeEndWS2.Bind(wx.adv.EVT_TIME_CHANGED, self.time_EndWS2)
self.dateBeginFT.Bind(wx.adv.EVT_DATE_CHANGED, self.date_BeginFT)
self.timeBeginFT.Bind(wx.adv.EVT_TIME_CHANGED, self.time_BeginFT)
self.dateEndFT.Bind(wx.adv.EVT_DATE_CHANGED, self.date_EndFT)
self.timeEndFT.Bind(wx.adv.EVT_TIME_CHANGED, self.time_EndFT)
self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
def __del__(self):
pass
def OnEraseBackground(self, evt):
"""
Add a picture to the background
"""
# yanked from ColourDB.py
dc = evt.GetDC()
if not dc:
dc = wx.ClientDC(self)
rect = self.GetUpdateRegion().GetBox()
dc.SetClippingRect(rect)
dc.Clear()
bmp = wx.Bitmap("AMD.png")
dc.DrawBitmap(bmp, 0, 0)
# Virtual event handlers, overide them in your derived class
def clickBtn_Report1(self, event):
a = self.m_checkBox1.IsChecked()
b = self.m_checkBox2.IsChecked()
c = self.m_checkBox3.IsChecked()
# d = reportGrid(None)
if (a == True and b == True):
fileName = self.get_Path(None)
fileName2 = self.get_PathWS2(None)
dataWS = F_WaferSort1.report(self, fileName)
dataWS2 = F_WaferSort2.report(self, fileName2)
grid = reportFrame(None, list=dataWS, list2=dataWS2)
elif (a == True and b == False):
fileName = self.get_Path(None)
fileName2 = self.get_PathWS2(None)
dataWS = F_WaferSort1.report(self, fileName)
grid = reportFrame(None, list=dataWS)
# print(self.m_checkBox1.IsChecked())
# print(self.m_checkBox2.IsChecked())
def get_Path(self, event):
a = self.m_filePicker1.GetPath()
a = a.split("\\")
a = "\\\\".join(a)
return a
def get_PathWS2(self, event):
a = self.m_filePicker2.GetPath()
a = a.split("\\")
a = "\\\\".join(a)
return a
def get_PathFT(self, event):
a = self.m_filePicker3.GetPath()
a = a.split("\\")
a = "\\\\".join(a)
return a
def date_Begin(self, event):
aStringDate = self.dateBegin.GetValue().Format("%m-%d-%y")
return aStringDate
def time_Begin(self):
aStringTime = self.timeBegin.GetTime()
timeNotation = " {0}:{1}:{2}".format(str(aStringTime[0]),
str(aStringTime[1]),
str(aStringTime[2]))
return timeNotation
def date_End(self, event):
aStringDate = self.dateEnd.GetValue().Format("%m-%d-%y")
return aStringDate
def time_End(self):
aStringTime = self.timeEnd.GetTime()
timeNotation = " {0}:{1}:{2}".format(str(aStringTime[0]),
str(aStringTime[1]),
str(aStringTime[2]))
return timeNotation
return aStringTime
def date_BeginWS2(self, event):
aStringDate = self.dateBeginWS2.GetValue().Format("%m-%d-%y")
return aStringDate
def time_BeginWS2(self):
aStringTime = self.timeBeginWS2.GetTime()
timeNotation = " {0}:{1}:{2}".format(str(aStringTime[0]),
str(aStringTime[1]),
str(aStringTime[2]))
return timeNotation
def date_EndWS2(self, event):
aStringDate = self.dateEndWS2.GetValue().Format("%m-%d-%y")
return aStringDate
def time_EndWS2(self):
aStringTime = self.timeEndWS2.GetTime()
timeNotation = " {0}:{1}:{2}".format(str(aStringTime[0]),
str(aStringTime[1]),
str(aStringTime[2]))
return timeNotation
return aStringTime
def date_BeginFT(self, event):
aStringDate = self.dateBeginFT.GetValue().Format("%m-%d-%y")
return aStringDate
def time_BeginFT(self):
aStringTime = self.timeBeginFT.GetTime()
timeNotation = " {0}:{1}:{2}".format(str(aStringTime[0]),
str(aStringTime[1]),
str(aStringTime[2]))
return timeNotation
def date_EndFT(self, event):
aStringDate = self.dateEndFT.GetValue().Format("%m-%d-%y")
return aStringDate
def time_EndFT(self):
aStringTime = self.timeEndFT.GetTime()
timeNotation = " {0}:{1}:{2}".format(str(aStringTime[0]),
str(aStringTime[1]),
str(aStringTime[2]))
return timeNotation
return aStringTime
def clickBtn_Generate(self, event):
fileName = self.get_Path(None)
a = self.date_Begin(None)
b = self.time_Begin()
c = self.date_End(wx.adv.DateEvent())
d = self.time_End()
list = []
list.append(a)
list.append(b)
list.append(c)
list.append(d)
startDate = list[0] + list[1]
endDate = list[2] + list[3]
startDateDateTime = datetime.strptime(startDate, "%m-%d-%y %H:%M:%S")
endDateDateTime = datetime.strptime(endDate, "%m-%d-%y %H:%M:%S")
print(startDateDateTime)
print(endDateDateTime)
if (endDateDateTime < startDateDateTime):
frame = badDates(None)
frame.Show()
else:
frame = F_WaferSort1(None, startDate, endDate, fileName)
frame.getXYD()
frame.creatFirstFrame()
event.Skip()
def clickBtn_GenerateWS2(self, event):
fileName = self.get_PathWS2(None)
a = self.date_BeginWS2(None)
b = self.time_BeginWS2()
c = self.date_EndWS2(wx.adv.DateEvent())
d = self.time_EndWS2()
list = []
list.append(a)
list.append(b)
list.append(c)
list.append(d)
startDate = list[0] + list[1]
endDate = list[2] + list[3]
startDateDateTime = datetime.strptime(startDate, "%m-%d-%y %H:%M:%S")
endDateDateTime = datetime.strptime(endDate, "%m-%d-%y %H:%M:%S")
if (endDateDateTime < startDateDateTime):
frame = badDates(None)
frame.Show()
else:
frame = F_WaferSort2(None, startDate, endDate, fileName)
frame.getXYD()
frame.creatFirstFrame()
event.Skip()
def clickBtn_GenerateFT(self, event):
fileName = self.get_PathFT(None)
a = self.date_BeginFT(None)
b = self.time_BeginFT()
c = self.date_EndFT(wx.adv.DateEvent())
d = self.time_EndFT()
list = []
list.append(a)
list.append(b)
list.append(c)
list.append(d)
startDate = list[0] + list[1]
endDate = list[2] + list[3]
startDateDateTime = datetime.strptime(startDate, "%m-%d-%y %H:%M:%S")
endDateDateTime = datetime.strptime(endDate, "%m-%d-%y %H:%M:%S")
print(startDateDateTime)
print(endDateDateTime)
if (endDateDateTime < startDateDateTime):
frame = badDates(None)
frame.Show()
else:
frame = F_WaferSortFT(None, startDate, endDate, fileName)
frame.getXYD()
frame.creatFirstFrame()
event.Skip()
class MainFrame(wx.Frame):
""""""
# ----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, None, size=(740, 410))
panel = F_Main(self)
self.Center()
below is the image of how it looks. Im prettu sure I can resize the image to be bigger but im sure i'll have the same problem once you maximize the window
the link to the turorial I followed is https://www.blog.pythonlibrary.org/2010/03/18/wxpython-putting-a-background-image-on-a-panel/
You could use the Scale function of wx.Image to set the image to the size of the window.
def OnEraseBackground(self, evt):
"""
Add a picture to the background
"""
# yanked from ColourDB.py
dc = evt.GetDC()
if not dc:
dc = wx.ClientDC(self)
rect = self.GetUpdateRegion().GetBox()
dc.SetClippingRect(rect)
dc.Clear()
w,h = self.GetSize()
bmp = wx.Bitmap("AMD.png")
image = bmp.ConvertToImage()
bmp = wx.Bitmap(image.Scale(w,h))
dc.DrawBitmap(bmp, 0, 0)
I'm trying to build an application in Python using wxpython library.
I would like to add and remove widgets dinamically like in the picture
(https://i.stack.imgur.com/bNB3q.png) so that i can add and remove how many StaticBoxSizer I want.
I got a good result in adding widgets while I can't get the way to remove the widgets. I'm successfull in destroying every widget in the StaticBoxSizer but I'm not able to destroy the container StaticBoxSizer itself: if I try to add many blocks and then removing one of them, in the onRemoveMaster method something happens and Python crash.
My code:
import wx
import wx.xrc
import wx.aui
class Example(wx.Frame):
def __init__(self, parent, title):
super(Example, self).__init__(parent, title=title,
size = wx.Size( 726,624 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL)
self.InitUI()
self.Centre()
self.Show()
def InitUI(self):
self.number_of_added = 0
self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
#Setup MenuBar
self.m_menubar1 = wx.MenuBar( 0 )
self.m_menu1 = wx.Menu()
self.m_menubar1.Append( self.m_menu1, u"MyMenu" )
self.m_menu2 = wx.Menu()
self.m_menubar1.Append( self.m_menu2, u"MyMenu" )
self.SetMenuBar( self.m_menubar1 )
#Setup Main Container
MainSizer = wx.BoxSizer( wx.VERTICAL )
self.ScrolledWindow = wx.ScrolledWindow( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.HSCROLL|wx.VSCROLL )
self.ScrolledWindow.SetScrollRate( 1, 1 )
MainVerticalSizer = wx.BoxSizer( wx.VERTICAL )
self.m_auinotebook1 = wx.aui.AuiNotebook( self.ScrolledWindow, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.aui.AUI_NB_DEFAULT_STYLE )
#Costruzione Master Sequence Tab
self.MasterSequenceTab = wx.ScrolledWindow( self.m_auinotebook1, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.HSCROLL|wx.VSCROLL )
self.MasterSequenceTab.SetScrollRate( 1, 1 )
self.MasterVSizer = wx.BoxSizer( wx.VERTICAL )
MasterButtonSizer = wx.BoxSizer( wx.HORIZONTAL )
self.ButtonAdd = wx.Button( self.MasterSequenceTab, wx.ID_ANY, u"Add", wx.DefaultPosition, wx.DefaultSize, 0 )
MasterButtonSizer.Add( self.ButtonAdd, 0, wx.ALL, 5 )
self.ButtonAdd.Bind(wx.EVT_BUTTON, self.onAddMaster)
self.ButtonRemove = wx.Button( self.MasterSequenceTab, wx.ID_ANY, u"Remove", wx.DefaultPosition, wx.DefaultSize, 0 )
MasterButtonSizer.Add( self.ButtonRemove, 0, wx.ALL, 5 )
self.ButtonRemove.Bind(wx.EVT_BUTTON, self.onRemoveMaster)
self.MasterVSizer.Add( MasterButtonSizer, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALL, 5 )
self.onAddMaster(self)
self.m_auinotebook1.AddPage( self.MasterSequenceTab, u"Master Sequence", False )
#Finalizzazione finestre
MainVerticalSizer.Add( self.m_auinotebook1, 1, wx.EXPAND, 5 )
self.ScrolledWindow.SetSizer( MainVerticalSizer )
self.ScrolledWindow.Layout()
MainVerticalSizer.Fit( self.ScrolledWindow )
MainSizer.Add( self.ScrolledWindow, 1, wx.EXPAND |wx.ALL, 5 )
self.SetSizer( MainSizer )
self.Layout()
self.Centre( wx.BOTH )
def onAddMaster(self, event):
self.number_of_added += 1
self.MastersbSizerAdded = wx.StaticBoxSizer( wx.StaticBox( self.MasterSequenceTab, 100+self.number_of_added, wx.EmptyString ),wx.VERTICAL )
self.MasterCheckEnableAdded = wx.CheckBox( self.MastersbSizerAdded.GetStaticBox(), 200+self.number_of_added, u"Enable", wx.DefaultPosition, wx.DefaultSize, 0 )
self.MasterCheckEnableAdded.SetValue(True)
self.MastersbSizerAdded.Add( self.MasterCheckEnableAdded, 0, wx.ALIGN_RIGHT|wx.ALL, 5 )
MasterfgSizerAdded = wx.FlexGridSizer( 0, 2, 0, 0 )
MasterfgSizerAdded.SetFlexibleDirection( wx.BOTH )
MasterfgSizerAdded.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED )
self.MasterTextNomeAdded = wx.StaticText( self.MastersbSizerAdded.GetStaticBox(), 1000+self.number_of_added, u"Nome", wx.DefaultPosition, wx.DefaultSize, 0 )
self.MasterTextNomeAdded.Wrap( -1 )
MasterfgSizerAdded.Add( self.MasterTextNomeAdded, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5 )
self.MasterCtrlNomeAdded = wx.TextCtrl( self.MastersbSizerAdded.GetStaticBox(), 300+self.number_of_added, wx.EmptyString, wx.DefaultPosition, wx.Size( 566,-1 ), 0 )
MasterfgSizerAdded.Add( self.MasterCtrlNomeAdded, 0, wx.ALL, 5 )
self.MasterTextDescrizioneAdded = wx.StaticText( self.MastersbSizerAdded.GetStaticBox(), 1100+self.number_of_added, u"Descrizione ", wx.DefaultPosition, wx.DefaultSize, 0 )
self.MasterTextDescrizioneAdded.Wrap( -1 )
MasterfgSizerAdded.Add( self.MasterTextDescrizioneAdded, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5 )
self.MasterCtrlDescrizione1 = wx.TextCtrl( self.MastersbSizerAdded.GetStaticBox(), 400+self.number_of_added, wx.EmptyString, wx.DefaultPosition, wx.Size( 566,-1 ), 0 )
MasterfgSizerAdded.Add( self.MasterCtrlDescrizione1, 0, wx.ALL, 5 )
self.MastersbSizerAdded.Add( MasterfgSizerAdded, 0, wx.ALL, 5 )
MasterfgSizerAdded2 = wx.FlexGridSizer( 3, 6, 0, 0 )
MasterfgSizerAdded2.SetFlexibleDirection( wx.BOTH )
MasterfgSizerAdded2.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED )
self.MasterTextSubjectAdded = wx.StaticText( self.MastersbSizerAdded.GetStaticBox(), 1200+self.number_of_added, u"Subject Area", wx.DefaultPosition, wx.DefaultSize, 0 )
self.MasterTextSubjectAdded.Wrap( -1 )
MasterfgSizerAdded2.Add( self.MasterTextSubjectAdded, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5 )
self.MasterCtrlSubjectAdded = wx.TextCtrl( self.MastersbSizerAdded.GetStaticBox(), 500+self.number_of_added, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )
MasterfgSizerAdded2.Add( self.MasterCtrlSubjectAdded, 0, wx.ALL, 5 )
self.MasterTextAlimentanteAdded = wx.StaticText( self.MastersbSizerAdded.GetStaticBox(), 1300+self.number_of_added, u" Alimentante", wx.DefaultPosition, wx.DefaultSize, 0 )
self.MasterTextAlimentanteAdded.Wrap( -1 )
MasterfgSizerAdded2.Add( self.MasterTextAlimentanteAdded, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5 )
self.MasterCtrlAlimentanteAdded = wx.TextCtrl( self.MastersbSizerAdded.GetStaticBox(), 600+self.number_of_added, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )
MasterfgSizerAdded2.Add( self.MasterCtrlAlimentanteAdded, 0, wx.ALL, 5 )
self.MasterTextGroupAdded = wx.StaticText( self.MastersbSizerAdded.GetStaticBox(), 1400+self.number_of_added, u" Num group", wx.DefaultPosition, wx.DefaultSize, 0 )
self.MasterTextGroupAdded.Wrap( -1 )
MasterfgSizerAdded2.Add( self.MasterTextGroupAdded, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5 )
self.MasterCtrlGroupAdded = wx.TextCtrl( self.MastersbSizerAdded.GetStaticBox(), 700+self.number_of_added, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )
MasterfgSizerAdded2.Add( self.MasterCtrlGroupAdded, 0, wx.ALL, 5 )
self.MasterTextSchedulingAdded = wx.StaticText( self.MastersbSizerAdded.GetStaticBox(), 1500+self.number_of_added, u"Schedulazione", wx.DefaultPosition, wx.DefaultSize, 0 )
self.MasterTextSchedulingAdded.Wrap( -1 )
MasterfgSizerAdded2.Add( self.MasterTextSchedulingAdded, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5 )
MasterCtrlSchedulingChoicesAdded = [ u"G", u"S", u"D", u"Q", u"M", u"BM", u"TM", u"SM", u"A" ]
self.MasterCtrlSchedulingAdded = wx.Choice( self.MastersbSizerAdded.GetStaticBox(), 800+self.number_of_added, wx.DefaultPosition, wx.DefaultSize, MasterCtrlSchedulingChoicesAdded, 0 )
self.MasterCtrlSchedulingAdded.SetSelection( 0 )
MasterfgSizerAdded2.Add( self.MasterCtrlSchedulingAdded, 0, wx.ALL, 5 )
self.MasterTextValidoAdded = wx.StaticText( self.MastersbSizerAdded.GetStaticBox(), 1600+self.number_of_added, u" Record valido", wx.DefaultPosition, wx.DefaultSize, 0 )
self.MasterTextValidoAdded.Wrap( -1 )
MasterfgSizerAdded2.Add( self.MasterTextValidoAdded, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5 )
MasterCtrlValido1Choices = [ u"Y", u"N" ]
self.MasterCtrlValidoAdded = wx.Choice( self.MastersbSizerAdded.GetStaticBox(), 900+self.number_of_added, wx.DefaultPosition, wx.DefaultSize, MasterCtrlValido1Choices, 0 )
self.MasterCtrlValidoAdded.SetSelection( 0 )
MasterfgSizerAdded2.Add( self.MasterCtrlValidoAdded, 0, wx.ALL, 5 )
self.MastersbSizerAdded.Add( MasterfgSizerAdded2, 0, wx.ALL, 5 )
self.MasterVSizer.Add( self.MastersbSizerAdded, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 5 )
self.MasterSequenceTab.SetSizer( self.MasterVSizer )
self.MasterSequenceTab.Layout()
self.MasterVSizer.Fit( self.MasterSequenceTab )
def onRemoveMaster(self, event):
for i in range(16,0,-1):
button = 100*i+self.number_of_added
widget = self.MasterSequenceTab.FindWindowById(button)
widget.Destroy()
self.MasterSequenceTab.SetSizer( self.MasterVSizer )
self.MasterSequenceTab.Layout()
self.MasterVSizer.Fit( self.MasterSequenceTab )
self.number_of_added -= 1
if __name__ == '__main__':
app = wx.App()
Example(None, title='Test')
app.MainLoop()
It would be much easier to create a new panel class with all those controls parented to it, and then just add and delete instances of the panel.
The panel instances could be stored in a list.
I have built a GUI using wxFormBuilder and want to dynamically add buttons to a sizer within the GUI. Here is the wxFormBuilder code.
# -*- coding: utf-8 -*-
###########################################################################
## Python code generated with wxFormBuilder (version Jun 17 2015)
## http://www.wxformbuilder.org/
##
## PLEASE DO "NOT" EDIT THIS FILE!
###########################################################################
import wx
import wx.xrc
###########################################################################
## Class HighVoltage
###########################################################################
class HighVoltage ( wx.Frame ):
def __init__( self, parent ):
wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 1031,530 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
self.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_ACTIVECAPTION ) )
bSizer84 = wx.BoxSizer( wx.VERTICAL )
self.m_panel70 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
bSizer85 = wx.BoxSizer( wx.HORIZONTAL )
self.m_staticText79 = wx.StaticText( self.m_panel70, wx.ID_ANY, u"HV Documentation", wx.DefaultPosition, wx.DefaultSize, 0 )
self.m_staticText79.Wrap( -1 )
self.m_staticText79.SetFont( wx.Font( 20, 70, 90, 92, False, "Century Gothic" ) )
bSizer85.Add( self.m_staticText79, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5 )
bSizer85.AddSpacer( ( 0, 0), 1, wx.EXPAND, 5 )
self.m_bitmap24 = wx.StaticBitmap( self.m_panel70, wx.ID_ANY, wx.Bitmap( u"LOGOtransSmall.png", wx.BITMAP_TYPE_ANY ), wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer85.Add( self.m_bitmap24, 0, wx.ALL, 5 )
self.m_panel70.SetSizer( bSizer85 )
self.m_panel70.Layout()
bSizer85.Fit( self.m_panel70 )
bSizer84.Add( self.m_panel70, 0, wx.EXPAND |wx.ALL, 5 )
self.m_panel71 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
bSizer86 = wx.BoxSizer( wx.VERTICAL )
bSizer86.AddSpacer( ( 0, 0), 1, wx.EXPAND, 5 )
self.m_panel73 = wx.Panel( self.m_panel71, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
bSizer86.Add( self.m_panel73, 0, wx.EXPAND |wx.ALL, 5 )
self.m_panel71.SetSizer( bSizer86 )
self.m_panel71.Layout()
bSizer86.Fit( self.m_panel71 )
bSizer84.Add( self.m_panel71, 1, wx.EXPAND |wx.ALL, 5 )
self.m_panel72 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
bSizer87 = wx.BoxSizer( wx.HORIZONTAL )
bSizer87.AddSpacer( ( 0, 0), 1, wx.EXPAND, 5 )
self.m_button65 = wx.Button( self.m_panel72, wx.ID_ANY, u"Exit", wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer87.Add( self.m_button65, 0, wx.ALL, 5 )
self.m_panel72.SetSizer( bSizer87 )
self.m_panel72.Layout()
bSizer87.Fit( self.m_panel72 )
bSizer84.Add( self.m_panel72, 0, wx.EXPAND |wx.ALL, 5 )
self.SetSizer( bSizer84 )
self.Layout()
self.Centre( wx.BOTH )
def __del__( self ):
pass
I want to add buttons to bSizer86 which is a child of m_panel71.
Here's what I've tried so far.
class HvDocs(HighVoltage):
def __init__(self, parent):
HighVoltage.__init__(self, parent)
con = sqlite3.connect('hsmanagement.sqlite')
cur = con.execute('SELECT employee FROM employees WHERE hv=1 ORDER BY employee')
result = cur.fetchall()
con.close()
print result
sizer = self.GetSizer()
print type(sizer)
for f in range(0, len(result) ):
sizer.Add(wx.Button(self, label=str(result[f][0]), id=int(f), size=(200, 40)), 2, wx.CENTER)
I have tried a few variations of sizer = self.GetSizer() such as sizer = self.m_panel71 and sizer = self.GetSizer(self.m_panel71) but all I can manage is to add the buttons to the top level sizer bSizer84. How do I gain access to bSizer86?
See the following minimal example how to find panels, buttons and sizers by name only. wxFormBuilder offers the possibility to set the wx.Window property window_name for GUI elements you want to keep track on. You should be able to find control you need to know having this name with parent.FindWindowByName(…) without relying on a class attribute.
import wx
TOK_PNL = 'window_name pnl'
TOK_BTN = 'window_name btn'
def on_btn(evt, parent):
btn = parent.FindWindowByName(TOK_BTN)
pnl = parent.FindWindowByName(TOK_PNL)
newbtn = wx.Button(pnl, -1, 'newbtn')
szsub = btn.GetContainingSizer()
szsub.Add(newbtn, 1, wx.EXPAND|wx.ALL, 4)
pnl.Layout()
class testfrm(wx.Frame):
def __init__(self, *args, **kwds):
wx.Frame.__init__(self, *args, **kwds)
pnl = wx.Panel(self, -1)
pnl.SetName(TOK_PNL)
btn = wx.Button(pnl, -1, 'Add Button')
btn.SetName(TOK_BTN)
szmain = wx.BoxSizer(wx.VERTICAL)
szsub = wx.BoxSizer(wx.HORIZONTAL)
szsub.Add(btn, 0, wx.EXPAND|wx.ALL, 4)
szmain.Add(szsub)
pnl.SetSizer(szmain)
the_parent = self
btn.Bind(wx.EVT_BUTTON, lambda evt: on_btn(evt, the_parent))
if __name__ == '__main__':
app = wx.App(redirect=False)
frm = testfrm(None, -1, 'testfrm')
frm.Show()
app.MainLoop()
After digging a bit further and playing around I finally solved my problem with the following code
sizer = self.m_button67.GetContainingSizer()
self.m_button67.Destroy()
self.m_staticText = wx.StaticText( self.m_panel74, wx.ID_ANY, label= "Ladder ID")
sizer.Add( self.m_staticText, 0, wx.ALL, 5 )
self.m_staticText = wx.StaticText( self.m_panel74, wx.ID_ANY, label= "Engineer")
sizer.Add( self.m_staticText, 0, wx.ALL, 5 )
self.m_staticText = wx.StaticText( self.m_panel74, wx.ID_ANY, label= "Description")
sizer.Add( self.m_staticText, 0, wx.ALL, 5 )
self.m_staticText = wx.StaticText( self.m_panel74, wx.ID_ANY, label= "Last Check")
sizer.Add( self.m_staticText, 0, wx.ALL, 5 )
self.m_staticText = wx.StaticText( self.m_panel74, wx.ID_ANY, label= "Next Check")
sizer.Add( self.m_staticText, 0, wx.ALL, 5 )
for f in range(0, len(ladder_data)):
self.m_button = wx.Button( self.m_panel74, id=int(f), label=str(ladder_data[f][0]))
self.Bind(wx.EVT_BUTTON, self.detect_on_button)
sizer.Add( self.m_button, 0, wx.ALL, 5 )
self.m_staticText = wx.StaticText( self.m_panel74, wx.ID_ANY, label= str(ladder_data[f][1]))
sizer.Add( self.m_staticText, 0, wx.ALL, 5 )
self.m_staticText = wx.StaticText( self.m_panel74, wx.ID_ANY, label= str(ladder_data[f][2]))
sizer.Add( self.m_staticText, 0, wx.ALL, 5 )
self.m_staticText = wx.StaticText( self.m_panel74, wx.ID_ANY, label= str(ladder_data[f][3]))
sizer.Add( self.m_staticText, 0, wx.ALL, 5 )
self.m_staticText = wx.StaticText( self.m_panel74, wx.ID_ANY, label= str(ladder_data[f][4]))
sizer.Add( self.m_staticText, 0, wx.ALL, 5 )
self.m_panel74.SetSizer( sizer )
self.m_panel74.Layout()
sizer.Fit( self.m_panel74 )
The key really was the discovery of GetContainingSizer().
Using this with a dummy button set up in wxFormBuilder (self.m_button67)
sizer = self.m_button67.GetContainingSizer()
gets you the sizer
remove the dummy button with
self.m_button67.Destroy()
add you widgets with
self.m_staticText = wx.StaticText( self.m_panel74, wx.ID_ANY, label= str(ladder_data[f][1]))
sizer.Add( self.m_staticText, 0, wx.ALL, 5 )
and the layout is completed with
self.m_panel74.SetSizer( sizer )
self.m_panel74.Layout()
sizer.Fit( self.m_panel74 )
Hope this help anyone with the same problem.
Maybe a little late,
I believe you are using GetSizer on Wrong element.
Try switching sizer = self.GetSizer() by sizer = self.m_panel71.GetSizer()
I am splitting a dialog box into 2 sections and using grid sizer to show list separately in section 1. I also use the length of list to create radiobox to hold three buttons. But with following script I am unable to show scroll bar to see full list of items. Any suggestions to fix it would be appreciative.
import wx
# I have following list available: lut_code
class MyFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, "Modify Hydrologic Condition", wx.DefaultPosition, wx.Size(900, 600))
splitter = wx.SplitterWindow(self, -1)
scroll1 = wx.ScrolledWindow(splitter, -1)
scroll1.SetBackgroundColour(wx.WHITE)
scroll1.SetVirtualSize(scroll1.GetBestSize() + (250,250))
scroll1.SetScrollRate(10,10)
grid_sizer = wx.GridSizer( 0, 8, 0, 0 )
self.head1 = wx.StaticText(scroll1, wx.ID_ANY, u"Code", (15,5))
self.head1.Wrap( -1 )
grid_sizer.Add( self.head1, 0, wx.ALL, 5 )
v = 0
for lu in lut_code:
v += 40
self.column11 = wx.StaticText(scroll1, wx.ID_ANY, str(lu), (15,v))
self.column11.Wrap( -1 )
grid_sizer.Add( self.column11, 0, wx.ALL, 5 )
rb = 0
radio1Choices = ['F','G','P']
for i in range(1,len(lut_code)):
rb += 40
self.radio1 = wx.RadioBox(scroll1, wx.ID_ANY, wx.EmptyString, (550,rb), (30,5), radio1Choices, 3, wx.RA_SPECIFY_COLS | wx.NO_BORDER)
self.radio1.SetSelection( 0 )
grid_sizer.Add( self.radio1, 0, wx.ALL, 5)
scroll2 = wx.ScrolledWindow(splitter,-1)
scroll2.SetBackgroundColour("light-grey")
message = """Blank"""
wx.StaticText(scroll2, -1,message, (15,150))
splitter.SplitVertically(scroll1,scroll2,-220)
def OnClose(self, event):
self.Show(False)
class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(None, -1, 'splitterwindow.py')
frame.Show(True)
self.SetTopWindow(frame)
return True
app = MyApp(0)
app.MainLoop()
you need to add in your program below scroll2 =wx.ScrolledWindow(splitter,-1)
scroll1.SetVirtualSize(scroll1.GetBestSize())
import wx
# I have following list available: lut_code
class MyFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, "Modify Hydrologic Condition", wx.DefaultPosition, wx.Size(900, 500))
splitter = wx.SplitterWindow(self, -1)
scroll1 = wx.ScrolledWindow(splitter, -1)
scroll1.SetBackgroundColour(wx.WHITE)
#scroll1.SetVirtualSize(scroll1.GetBestSize() + (250,250))
scroll1.SetScrollRate(1,1)
grid_sizer = wx.GridSizer( 0, 8, 0, 0 )
self.head1 = wx.StaticText(scroll1, wx.ID_ANY, u"Code", (15,5))
self.head1.Wrap( -1 )
grid_sizer.Add( self.head1, 0, wx.ALL, 5 )
v = 0
lut_code=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
for lu in lut_code:
v += 40
self.column11 = wx.StaticText(scroll1, wx.ID_ANY, str(lu), (15,v))
self.column11.Wrap( -1 )
grid_sizer.Add( self.column11, 0, wx.ALL, 5 )
rb = 0
radio1Choices = ['F','G','P']
for i in range(0,len(lut_code)):
rb += 40
self.radio1 = wx.RadioBox(scroll1, wx.ID_ANY, wx.EmptyString, (550,rb), (30,5), radio1Choices, 3, wx.RA_SPECIFY_COLS | wx.NO_BORDER)
self.radio1.SetSelection( 0 )
grid_sizer.Add( self.radio1, 0, wx.ALL, 5)
scroll2 =wx.ScrolledWindow(splitter,-1)
scroll1.SetVirtualSize(scroll1.GetBestSize())# + (250,250))
#wx.SetupScrolling(self, scroll_x=True, scroll_y=True, rate_x=20, rate_y=20, scrollToTop=True)
scroll2.SetBackgroundColour("light-grey")
message = """Blank"""
wx.StaticText(scroll2, -1,message, (15,150))
splitter.SplitVertically(scroll1,scroll2,-220)
def OnClose(self, event):
self.Show(False)
class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(None, -1, 'splitterwindow.py')
frame.Show(True)
self.SetTopWindow(frame)
return True
app = MyApp(0)
app.MainLoop()
output:
Set the ScrolledWindow's SetVirtualSize after adding the items, so the size can be calculated to include them.
Am working with multiple wx.Choice control in wxPython and I needed the make a reset button to restore the default option “-- Select --” when clicked.
Am unable to achieve that, the closest I came is to reset to empty options which is NOT what is want. I want the default option “-- Select --” to come up when reset button is pressed. See my code below.
data.py
import wx
class MyFrame1 ( wx.Frame ):
def __init__( self, parent ):
wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 250,300 ), style = wx.CAPTION|wx.CLOSE_BOX|wx.MINIMIZE_BOX|wx.SYSTEM_MENU|wx.TAB_TRAVERSAL )
self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
DataBox = wx.BoxSizer( wx.HORIZONTAL )
gSizer2 = wx.GridSizer( 0, 2, 0, 0 )
self.Color_Label = wx.StaticText( self, wx.ID_ANY, u"Color:", wx.DefaultPosition, wx.DefaultSize, 0 )
self.Color_Label.Wrap( -1 )
self.Color_Label.SetFont( wx.Font( 13, 70, 90, 90, False, wx.EmptyString ) )
gSizer2.Add( self.Color_Label, 0, wx.ALL, 5 )
Color_optionsChoices = [ u"-- Select --", u"Red", u"Green", u"Pink", u"Blue", u"Yellow", u"White", u"Brown" ]
self.Color_options = wx.Choice( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, Color_optionsChoices, 0 )
self.Color_options.SetSelection( 0 )
gSizer2.Add( self.Color_options, 0, wx.ALL, 5 )
self.Age = wx.StaticText( self, wx.ID_ANY, u"Age:", wx.DefaultPosition, wx.DefaultSize, 0 )
self.Age.Wrap( -1 )
self.Age.SetFont( wx.Font( 13, 70, 90, 90, False, wx.EmptyString ) )
gSizer2.Add( self.Age, 0, wx.ALL, 5 )
Age_optionsChoices = [ u"-- Select --", u"15", u"16", u"17", u"18", u"19", u"20", u"21", u"22", u"23", u"24", u"25", wx.EmptyString ]
self.Age_options = wx.Choice( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, Age_optionsChoices, 0 )
self.Age_options.SetSelection( 0 )
gSizer2.Add( self.Age_options, 0, wx.ALL, 5 )
self.Country = wx.StaticText( self, wx.ID_ANY, u"Country:", wx.DefaultPosition, wx.DefaultSize, 0 )
self.Country.Wrap( -1 )
self.Country.SetFont( wx.Font( 13, 70, 90, 90, False, wx.EmptyString ) )
gSizer2.Add( self.Country, 0, wx.ALL, 5 )
Country_optionsChoices = [ u"-- Select --", u"Mexico", u"Peru", u"India", u"USA", u"UK", u"Greece", u"Agentina", u"Greece", u"Brazil", u"Egypt" ]
self.Country_options = wx.Choice( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, Country_optionsChoices, 0 )
self.Country_options.SetSelection( 0 )
gSizer2.Add( self.Country_options, 0, wx.ALL, 5 )
self.Reset_button = wx.Button( self, wx.ID_ANY, u"Reset", wx.DefaultPosition, wx.DefaultSize, 0 )
gSizer2.Add( self.Reset_button, 0, wx.ALL, 5 )
self.Exit_button = wx.Button( self, wx.ID_ANY, u"Exit", wx.DefaultPosition, wx.DefaultSize, 0 )
gSizer2.Add( self.Exit_button, 0, wx.ALL, 5 )
DataBox.Add( gSizer2, 1, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL, 5 )
self.SetSizer( DataBox )
self.Layout()
self.Centre( wx.BOTH )
# Connect Events
self.Reset_button.Bind( wx.EVT_BUTTON, self.OnResetButton )
self.Exit_button.Bind( wx.EVT_BUTTON, self.OnExitButton )
def OnResetButton( self, event ):
# val = '-- Select --' # NOT WORKING
val = ' ' # THIS WORKS, BUT RESETS TO EMPTY CHOICE
self.Color_options.SetLabel(val)
self.Age_options.SetLabel(val)
self.Country_options.SetLabel(val)
def OnExitButton( self, event ):
self.Close()
app = wx.App(0)
MyFrame1(None).Show()
app.MainLoop()
Thanks for your time in advance.
Please reduce your source code to a minimal runnable example (explained below).
Answer: I am amazed that wx.Choice.SetLabel(' ') does something useful. What you want to do instead is:
self.Color_Options.SetStringSelection(val)
(see the wxWidgets documentation for wxChoice/wxItemContainer).
Remark: u'--Select--' is not '--Select--' in Python. As it happens, if the source encoding is set to UTF-8, wxPython will not complain and understand str encoden in UTF-8 as well as u''.
Minimal runnable example: As important as ever: Making your example as small as possible will teach you which parts are relevant for your question and which are not. In many cases, by writing the minimal example, I very often find the answer myself.
Minimising your example:
import wx
class MyFrame1(wx.Frame):
def __init__(self, *args, **kwds):
wx.Frame.__init__(self, *args, **kwds)
pnl = wx.Panel(self, wx.ID_ANY)
szmain = wx.BoxSizer(wx.VERTICAL)
color_choices = [u"-- Select --", u"Red", u"Green", u"Pink", u"Blue", u"Yellow", u"White", u"Brown"]
self.color_options = wx.Choice(pnl, wx.ID_ANY, choices=color_choices)
self.color_options.SetSelection(0)
self.reset_button = wx.Button(pnl, wx.ID_ANY, u"Reset")
szmain.Add(self.color_options, 0, wx.ALL|wx.EXPAND, 4)
szmain.Add(self.reset_button, 0, wx.ALL|wx.EXPAND, 4)
pnl.SetSizer(szmain)
self.reset_button.Bind( wx.EVT_BUTTON, self.OnResetButton )
def OnResetButton(self, event):
val = '-- Select --' # NOT WORKING
# val = ' ' # THIS WORKS, BUT RESETS TO EMPTY CHOICE
self.color_options.SetLabel(val)
app = wx.App(0)
MyFrame1(None).Show()
app.MainLoop()