wxpython sizers expands issue - python

I have a screen which has 6 grids as follows:
I'm adding a 7th grid.
This causes the screen to look like:
however I want the screen to be:
I tried to do it with flexgrid but it's not working.
This is my code:
sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
sizer_2.AddSpacer(10)
sizer_4 = wx.BoxSizer(wx.VERTICAL)
sizer_4.Add(self.grid1, 1, wx.EXPAND, 0)
sizer_4.AddSpacer(20)
sizer_4.Add(self.grid4, 1, wx.EXPAND, 0)
sizer_4.AddSpacer(20)
sizer_4.Add(self.grid7, 1, wx.EXPAND, 0)
sizer_5 = wx.BoxSizer(wx.VERTICAL)
sizer_5.Add(self.grid2, 1, wx.EXPAND, 0)
sizer_5.AddSpacer(20)
sizer_5.Add(self.grid5, 1, wx.EXPAND, 0)
sizer_6 = wx.BoxSizer(wx.VERTICAL)
sizer_6.Add(self.grid3, 1, wx.EXPAND, 0)
sizer_6.AddSpacer(20)
sizer_6.Add(self.grid6, 1, wx.EXPAND, 0)
sizer_3=wx.BoxSizer(wx.HORIZONTAL)
sizer_3.AddSpacer(20)
sizer_3.Add(sizer_4, 1, wx.EXPAND, 0)
sizer_3.AddSpacer(20)
sizer_3.Add(sizer_5, 1, wx.EXPAND, 0)
sizer_3.AddSpacer(20)
sizer_3.Add(sizer_6, 1, wx.EXPAND, 0)
sizer_1= wx.BoxSizer(wx.VERTICAL)
sizer_1.AddSpacer(10)
sizer_1.Add(sizer_2)
sizer_1.AddSpacer(20)
sizer_1.Add(sizer_3, 1, wx.EXPAND, 0)
self.SetSizer(sizer_1)
self.Layout()
What can I do?

I don't like the grid sizers because I find them pretty confusing. So I typically take something like this and draw boxes around the various groups. The boxes represent BoxSizers. Once I have that done, I know what to do and write my code accordingly. Here's how I would lay this out:
import wx
########################################################################
class GenericPanel(wx.Panel):
""""""
#----------------------------------------------------------------------
def __init__(self, parent, color):
"""Constructor"""
wx.Panel.__init__(self, parent, size=(200, 100))
self.SetBackgroundColour(color)
########################################################################
class MainPanel(wx.Panel):
""""""
#----------------------------------------------------------------------
def __init__(self, parent):
"""Constructor"""
wx.Panel.__init__(self, parent)
left_sizer = wx.BoxSizer(wx.VERTICAL)
for i in range(3):
panel = GenericPanel(self, 'red')
left_sizer.Add(panel, 0, wx.ALL, 5)
top_right_sizer = wx.BoxSizer(wx.HORIZONTAL)
for i in range(2):
panel = GenericPanel(self, 'green')
top_right_sizer.Add(panel, 0, wx.ALL, 5)
bottom_right_sizer = wx.BoxSizer(wx.HORIZONTAL)
for i in range(2):
panel = GenericPanel(self, 'blue')
bottom_right_sizer.Add(panel, 0, wx.ALL, 5)
stack_sizer = wx.BoxSizer(wx.VERTICAL)
stack_sizer.Add(top_right_sizer)
stack_sizer.Add(bottom_right_sizer)
main_sizer = wx.BoxSizer(wx.HORIZONTAL)
main_sizer.Add(left_sizer)
main_sizer.Add(stack_sizer)
main_sizer.AddStretchSpacer(prop=1)
self.SetSizer(main_sizer)
########################################################################
class MainFrame(wx.Frame):
""""""
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, None, title='Boxes', size=(700,400))
panel = MainPanel(self)
self.Show()
if __name__ == '__main__':
app = wx.App(False)
frame = MainFrame()
app.MainLoop()

Related

Show matplotlib plot in a wxpython panel and update on button push

I am trying to plot 1D txt files in a part of the window created using wxpython. For this purpose, a directory selection tool was included which lists all txt files. Now, I would like to select a txt file and plot it in a panel on the right side.
Further, I am thinking to implement a button that does some operations on the data and replot again.
What I have tried is this :
import os
import wx
import numpy as np
import matplotlib
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.figure import Figure
class mainFrame (wx.Frame):
def __init__(self):
super().__init__(None, id=wx.ID_ANY, title=u" test ",
size=wx.Size(854, 698),
style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL)
self.SetSizeHints(wx.Size(600, -1), wx.DefaultSize)
sizer = wx.BoxSizer(wx.VERTICAL)
self.panel = MainPanel(self, style=wx.TAB_TRAVERSAL)
self.Layout()
sizer.Add(self.panel, 1, wx.EXPAND, 0)
self.SetSizer(sizer)
self.Layout()
self.Centre()
# Connect Events
self.panel.dirPicker.Bind(wx.EVT_DIRPICKER_CHANGED, self.dirPickerOnDirChanged)
self.panel.listBox.Bind(wx.EVT_LISTBOX, self.listBoxOnListBox)
# ------------ Add widget program settings
# ------------ Call Populates
self.Show()
# Virtual event handlers, override them in your derived class
def dirPickerOnDirChanged(self, event):
self.FilePath = event.GetPath()
self.populateFileList()
def populateFileList(self):
self.panel.listBox.Clear()
allFiles = os.listdir(self.FilePath)
for file in allFiles:
if file.endswith('.txt'):
self.panel.listBox.Append(file)
def listBoxOnListBox(self, event):
try:
selected_file = event.GetString()
file_address = os.path.join(self.FilePath, selected_file)
# load file
data = np.loadtxt(file_address)
# select the first column
if isinstance(data, np.ndarray):
print("\tdata is np.array")
dim = data.ndim
if dim == 2:
input1D = data[:, 0]
else:
input1D = data
print(input1D.shape)
# plot here
else:
print("\tdata is not np.array")
except: # Do not use bare except
print("Some error.")
class MainPanel(wx.Panel):
def __init__(self, parent, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
self.FONT_11 = wx.Font(11, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL,
wx.FONTWEIGHT_NORMAL, False, "Consolas")
self.FONT_12 = wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL,
wx.FONTWEIGHT_NORMAL, False, wx.EmptyString)
self.FONT_13 = wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL,
wx.FONTWEIGHT_NORMAL, False, wx.EmptyString)
self.FONT_14 = wx.Font(14, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL,
wx.FONTWEIGHT_BOLD, False, "Consolas")
self.FONT_16 = wx.Font(16, wx.FONTFAMILY_SCRIPT, wx.FONTSTYLE_NORMAL,
wx.FONTWEIGHT_BOLD, False, wx.EmptyString)
sizer = wx.BoxSizer(wx.VERTICAL)
quick_display = self._quick_display()
directory_sizer = self._directory_sizer()
list_box_sizer = self._list_box_sizer()
self.text_details = self._detail_input()
details_sizer = self._details_sizer()
status_sizer = self._status_sizer()
message_sizer = wx.BoxSizer(wx.VERTICAL)
message_sizer.Add(details_sizer, 1, wx.EXPAND, 5)
message_sizer.Add(status_sizer, 1, wx.EXPAND, 5)
sizer.Add(quick_display, 0, wx.EXPAND, 0)
sizer.Add(directory_sizer, 0, wx.EXPAND, 0)
sizer.Add(list_box_sizer, 1, wx.EXPAND, 0)
sizer.Add(message_sizer, 1, wx.EXPAND, 5)
self.SetSizer(sizer)
def _quick_display(self):
quick_display = wx.StaticText(self, label=u"quick display")
quick_display.Wrap(-1)
quick_display.SetFont(self.FONT_16)
return quick_display
def _directory_sizer(self):
sbSizerDir = wx.StaticBoxSizer(wx.StaticBox(self, label=u" working directory"))
self.dirPicker = wx.DirPickerCtrl(sbSizerDir.GetStaticBox(), message=u"Select a folder")
sbSizerDir.Add(self.dirPicker, 0, wx.ALL | wx.EXPAND, 5)
return sbSizerDir
def _list_box(self):
listBoxChoices = []
self.listBox = wx.ListBox(self, size=wx.Size(300, -1), choices=listBoxChoices)
self.listBox.SetMinSize(wx.Size(250, -1))
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.listBox, 1, wx.ALL, 10)
return sizer
def _plot_sizer(self):
self.panelPlot = PlotPanel(self)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.panelPlot, 1, wx.EXPAND | wx.ALL, 5)
return sizer
def _list_box_sizer(self):
file_list_sizer = self._list_box()
bSizer_plot = self._plot_sizer()
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(file_list_sizer, 1, wx.EXPAND, 0)
sizer.Add(bSizer_plot, 1, wx.EXPAND, 5)
bSizerSplitHor = wx.BoxSizer(wx.HORIZONTAL)
bSizerSplitHor.Add(sizer, 1, wx.EXPAND, 2)
bSizerSplit = wx.BoxSizer(wx.VERTICAL)
bSizerSplit.Add(bSizerSplitHor, 1, wx.EXPAND, 0)
return bSizerSplit
def _detail_label(self):
detail_label = wx.StaticText(self, label="Details")
detail_label.Wrap(-1)
detail_label.SetFont(self.FONT_14)
return detail_label
def _detail_input(self):
text_details = wx.TextCtrl(self, size=wx.Size(250, -1))
text_details.SetFont(self.FONT_11)
return text_details
def _button_sizer(self):
self.button = wx.Button(self, label=u"do some operation")
self.button.SetFont(self.FONT_13)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.button, 0, wx.ALL, 5)
return sizer
def _details_sizer(self):
detail_label = self._detail_label()
button_sizer = self._button_sizer()
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(detail_label, 0, wx.ALL, 5)
sizer.Add(self.text_details, 1, wx.EXPAND, 5)
sizer.Add(button_sizer, 1, wx.EXPAND, 5)
return sizer
def _status_sizer(self):
self.staticline3 = wx.StaticLine(self)
self.status_label = wx.StaticText(self, label=u"Status bar")
self.status_label.Wrap(-1)
self.status_label.SetFont(self.FONT_12)
self.staticline4 = wx.StaticLine(self)
self.textCtrl_status = wx.TextCtrl(self)
self.textCtrl_status.SetFont(self.FONT_11)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.staticline3, 0, wx.EXPAND | wx.ALL, 5)
sizer.Add(self.status_label, 0, wx.ALL, 5)
sizer.Add(self.staticline4, 0, wx.EXPAND | wx.ALL, 5)
sizer.Add(self.textCtrl_status, 0, wx.ALL | wx.EXPAND, 5)
status_sizer = wx.BoxSizer(wx.VERTICAL)
status_sizer.Add(sizer, 1, wx.EXPAND, 5)
return status_sizer
class PlotPanel(wx.Panel):
def __init__(self, parent, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
self.SetMinSize(wx.Size(100, -1))
if __name__ == "__main__":
app = wx.App(False)
frame = mainFrame()
app.MainLoop()
This creates a window as follows :
The right portion is assigned as a panel, and I not sure how to place the matplotlib plot in it. Thank you.
There are several good questions on SE probing this topic, such as Q1 and Q2; however, most are limited to the plot being shown on the main window.
wxGlade includes some wxPython / matplotlib examples. Use these as starting point.
https://github.com/wxGlade/wxGlade/tree/master/examples

two BoxSizers interfere

I have two BoxSizers, the first one
sizer = wx.BoxSizer (wx.VERTICAL)
sizer.Add (self.grid2, 1, wx.EXPAND)
panel2.SetSizer (sizer)
and another vertical BoxSizers, to the left of the button grid, both BoxSizers interfere.
vbox1 = wx.FlexGridSizer (rows = 1, cols = 3, hgap = 5, vgap = 5)
buttonsBox1 = wx.BoxSizer (wx.VERTICAL)
buttonsBox1.Add (self.buttonoborved)
vbox1.Add (buttonsBox1)
vbox1.Add (self.grid2)
vbox1.Add (midPan1, wx.ID_ANY, wx.EXPAND | wx.ALL, 20)
panel2.SetSizer (vbox1)
An error occurs - Adding a window already in a sizer, detach it first!
How can they be called at the same time.
Edit:
That are two BoxSizer, one in other, but how can be put buttons in there.
import wx
import wx.grid
from wx.lib.scrolledpanel import ScrolledPanel
class TestPanel(ScrolledPanel):
def __init__(self, parent):
ScrolledPanel.__init__(self, parent, wx.ID_ANY, size=(640, 480))
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self._create_table(), 1, wx.EXPAND | wx.ALL, 5)
self.SetSizer(self.sizer)
self.SetupScrolling()
self.SetAutoLayout(1)
def _create_table(self):
_table = wx.grid.Grid(self, -1)
_table.CreateGrid(0, 2)
for i in range(1723): # Work normally If I use 1722 rows
_table.AppendRows()
_table.SetCellValue(i, 0, str(i))
return _table
class TestFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY,
title="Scroll table", size=(640, 480))
self.fSizer = wx.BoxSizer(wx.VERTICAL)
self.fSizer.Add(TestPanel(self), 1, wx.EXPAND)
self.SetSizer(self.fSizer)
self.Show()
if __name__ == "__main__":
app = wx.App(False)
frame = TestFrame()
app.MainLoop()
It depends where you want to place the buttons but let's assume they should be at the bottom.
import wx
import wx.grid
from wx.lib.scrolledpanel import ScrolledPanel
class TestPanel(ScrolledPanel):
def __init__(self, parent):
ScrolledPanel.__init__(self, parent, wx.ID_ANY, size=(640, 480))
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self._create_table(), 1, wx.EXPAND | wx.ALL, 5)
self.b1 = wx.Button(self, -1, "Button 1")
self.b2 = wx.Button(self, -1, "Button 2")
self.b3 = wx.Button(self, -1, "Button 3")
button_sizer = wx.BoxSizer(wx.HORIZONTAL)
button_sizer.Add(self.b1)
button_sizer.Add(self.b2)
button_sizer.Add(self.b3)
self.sizer.Add(button_sizer)
self.SetSizer(self.sizer)
self.SetupScrolling()
self.SetAutoLayout(1)
def _create_table(self):
_table = wx.grid.Grid(self, -1)
_table.CreateGrid(0, 2)
for i in range(1723): # Work normally If I use 1722 rows
_table.AppendRows()
_table.SetCellValue(i, 0, str(i))
return _table
class TestFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY,
title="Scroll table", size=(640, 480))
self.fSizer = wx.BoxSizer(wx.VERTICAL)
self.fSizer.Add(TestPanel(self), 1, wx.EXPAND)
self.SetSizer(self.fSizer)
self.Show()
if __name__ == "__main__":
app = wx.App(False)
frame = TestFrame()
app.MainLoop()

Why lists cannot be used with wx.BoxSizer?

I wanted to use lists made by wx.BoxSizer elements to make my code more readable and easier to manage but for some reason wxpython cannot use this kind of lists.
So here I wrote a code that works well without using the lists:
import wx
class MyPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
vsizer = wx.BoxSizer(wx.VERTICAL)
hsizer1 = wx.BoxSizer(wx.HORIZONTAL)
hsizer2 = wx.BoxSizer(wx.HORIZONTAL)
hsizer3 = wx.BoxSizer(wx.HORIZONTAL)
ts = [wx.StaticText(self, -1, str(i)) for i in range(3)]
ct = [wx.TextCtrl(self, -1) for i in range(3)]
hsizer1.Add(ts[0], 1, wx.EXPAND)
hsizer2.Add(ts[1], 1, wx.EXPAND)
hsizer3.Add(ts[2], 1, wx.EXPAND)
hsizer1.Add(ct[0], 1, wx.EXPAND)
hsizer2.Add(ct[1], 1, wx.EXPAND)
hsizer3.Add(ct[2], 1, wx.EXPAND)
vsizer.Add(hsizer1, 1, wx.ALIGN_CENTER)
vsizer.Add(hsizer2, 1, wx.ALIGN_CENTER)
vsizer.Add(hsizer3, 1, wx.ALIGN_CENTER)
self.SetSizer(vsizer)
class MyFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent)
MyPanel(self)
self.Layout()
self.Show()
app = wx.App()
frame = MyFrame(None)
app.MainLoop()
With this code you'll obtain the desired layout.
But if I use lists and cycles everything goes wrong:
import wx
class MyPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
vsizer = wx.BoxSizer(wx.VERTICAL)
hsizer1 = [wx.BoxSizer(wx.HORIZONTAL)]*3
ts = [wx.StaticText(self, -1, str(i)) for i in range(3)]
ct = [wx.TextCtrl(self, -1) for i in range(3)]
for i in range(3):
hsizer1[i].Add(ts[i], 1, wx.EXPAND)
hsizer1[i].Add(ct[i], 1, wx.EXPAND)
for i in hsizer1:
vsizer.Add(i, 1, wx.ALIGN_CENTER)
self.SetSizer(vsizer)
class MyFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent)
MyPanel(self)
self.Layout()
self.Show()
app = wx.App()
frame = MyFrame(None)
app.MainLoop()
As you can see they should produce the very same output but the don't. My question then is: why lists cannot be used in this case?
The thing is, you have the list hsizer1, which contains the same object 3 times. So it does not quite matter if you add to hsizer[0], hsizer[1] or hsizer[2], you are always adding into the same sizer. To fix it:
hsizer1 = [wx.BoxSizer(wx.HORIZONTAL) for i in range(3)]
Or you could:
for i in range(3):
hsizer = wx.BoxSizer(wx.HORIZONTAL)
hsizer.Add(ts[i], 1, wx.EXPAND)
hsizer.Add(ct[i], 1, wx.EXPAND)
vsizer.Add(hsizer, 1, wx.ALIGN_CENTER)

wxPython middle align items in sizer

I am dynamically changing the number of wx objects in my GUI. The code is working but the alignment of the objects is not perfect. The static text objects are not middle aligned with the text objects.
Notice that the word 'if' is not perfectly aligned with 'field name'.
Code:
import wx
########################################################################
class MyPanel(wx.Panel):
""""""
#----------------------------------------------------------------------
def __init__(self, parent):
"""Constructor"""
wx.Panel.__init__(self, parent)
self.numRows = 0
self.frame = parent
#create sizers
self.mainSizer = wx.BoxSizer(wx.VERTICAL)
controlSizer = wx.BoxSizer(wx.HORIZONTAL)
self.colSizer = wx.BoxSizer(wx.VERTICAL)
self.addButton = wx.Button(self, label="Add")
self.addButton.Bind(wx.EVT_BUTTON, self.onAddWidget)
controlSizer.Add(self.addButton, 0, wx.CENTER|wx.ALL, 5)
self.removeButton = wx.Button(self, label="Remove")
self.removeButton.Bind(wx.EVT_BUTTON, self.onRemoveWidget)
controlSizer.Add(self.removeButton, 0, wx.CENTER|wx.ALL, 5)
self.mainSizer.Add(controlSizer, 0, wx.CENTER)
self.mainSizer.Add(self.colSizer, 0, wx.CENTER|wx.ALL, 10)
self.SetSizer(self.mainSizer)
#----------------------------------------------------------------------
def onAddWidget(self, event):
""""""
self.numRows += 1
#create the objects
rowSizer =wx.BoxSizer(wx.HORIZONTAL)
ifText = wx.StaticText(self, -1, 'If')
fieldBox1 = wx.TextCtrl(self, -1, 'Field Name')
dropDown1 = wx.Choice(self, -1, choices=['<', '<=', '=', '>=', '>'])
fieldBox2 = wx.TextCtrl(self, -1, 'Field Name')
thenText = wx.StaticText(self, -1, 'Then')
fieldBox3 = wx.TextCtrl(self, -1, 'Field Name')
#create a list of all the objects
objects = [ifText, fieldBox1, dropDown1, fieldBox2, thenText, fieldBox3]
#add object to row sizer
for myObject in objects:
rowSizer.Add(myObject, 0, wx.ALL, 5)
#add the objects to the sizer
self.colSizer.Add(rowSizer, 0, wx.ALL, 5)
self.frame.fSizer.Layout()
self.frame.Fit()
#----------------------------------------------------------------------
def onRemoveWidget(self, event):
""""""
if self.colSizer.GetChildren():
self.colSizer.Hide(self.numRows-1)
self.colSizer.Remove(self.numRows-1)
self.numRows -= 1
self.frame.fSizer.Layout()
self.frame.Fit()
########################################################################
class MyFrame(wx.Frame):
""""""
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, parent=None, title="Add / Remove Buttons")
self.fSizer = wx.BoxSizer(wx.VERTICAL)
panel = MyPanel(self)
self.fSizer.Add(panel, 1, wx.EXPAND)
self.SetSizer(self.fSizer)
self.Fit()
self.Show()
#----------------------------------------------------------------------
if __name__ == "__main__":
app = wx.App(False)
frame = MyFrame()
app.MainLoop()
del app
Please could someone advise on how I can fix this alignment issue.
Thanks a lot in advance!
Duh! It turns out I just needed to change the alignment when adding items to the row sizer.
rowSizer.Add(myObject, 0, wx.ALIGN_CENTER, 5)

wxpython how to recreate grid?

I want to recreate a grid. For example: old grid is 4x4, I want change it to 5x5.
Here is my code:
import wx
import wx.xrc
import wx.grid
class MyFrame2(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=wx.EmptyString, pos=wx.DefaultPosition,
size=wx.Size(500, 300), style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL)
bSizer4 = wx.BoxSizer(wx.VERTICAL)
self.m_grid2 = wx.grid.Grid(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, 0)
# Grid
self.m_grid2.CreateGrid(4, 4)
bSizer4.Add(self.m_grid2, 0, wx.ALL, 5)
self.m_button3 = wx.Button(self, wx.ID_ANY, u"MyButton", wx.DefaultPosition, wx.DefaultSize, 0)
bSizer4.Add(self.m_button3, 0, wx.ALL, 5)
self.m_button3.Bind(wx.EVT_BUTTON, self.OnClick)
self.SetSizer(bSizer4)
self.Layout()
def OnClick(self, event):
self.m_grid2.CreateGrid(5, 5)
self.Layout()
app = wx.App()
frame = MyFrame2(None)
frame.Show(True)
app.MainLoop()
It raise an error when I run that:
File "C:\Python27\lib\site-packages\wx-3.0-msw\wx\grid.py", line 1221, in CreateGrid
return _grid.Grid_CreateGrid(*args, **kwargs)
wx._core.PyAssertionError: C++ assertion "!m_created" failed at ..\..\src\generic\grid.cpp(2325) in wxGrid::CreateGrid(): wxGrid::CreateGrid or wxGrid::SetTable called more than once
It seems I can't recreate this grid again. How can do this job?
If you don't want to Append the rows and columns, then you'll just have to recreate the grid itself. Here's a fairly simple demo that demonstrates how to do that:
import wx
import wx.grid as gridlib
########################################################################
class MyGrid(gridlib.Grid):
#----------------------------------------------------------------------
def __init__(self, parent, rows, cols):
gridlib.Grid.__init__(self, parent)
self.CreateGrid(rows, cols)
########################################################################
class MyPanel(wx.Panel):
""""""
#----------------------------------------------------------------------
def __init__(self, parent):
"""Constructor"""
wx.Panel.__init__(self, parent)
self.grid_created = False
row_sizer = wx.BoxSizer(wx.HORIZONTAL)
col_sizer = wx.BoxSizer(wx.HORIZONTAL)
self.main_sizer = wx.BoxSizer(wx.VERTICAL)
rows_lbl = wx.StaticText(self, label="Rows", size=(30, -1))
row_sizer.Add(rows_lbl, 0, wx.ALL|wx.CENTER, 5)
self.rows = wx.TextCtrl(self)
row_sizer.Add(self.rows, 0, wx.ALL|wx.EXPAND, 5)
cols_lbl = wx.StaticText(self, label="Cols", size=(30, -1))
col_sizer.Add(cols_lbl, 0, wx.ALL|wx.CENTER, 5)
self.cols = wx.TextCtrl(self)
col_sizer.Add(self.cols, 0, wx.ALL|wx.EXPAND, 5)
grid_btn = wx.Button(self, label="Create Grid")
grid_btn.Bind(wx.EVT_BUTTON, self.create_grid)
self.main_sizer.Add(row_sizer, 0, wx.EXPAND)
self.main_sizer.Add(col_sizer, 0, wx.EXPAND)
self.main_sizer.Add(grid_btn, 0, wx.ALL|wx.CENTER, 5)
self.SetSizer(self.main_sizer)
#----------------------------------------------------------------------
def create_grid(self, event):
""""""
rows = int( self.rows.GetValue() )
cols = int( self.cols.GetValue() )
if self.grid_created:
for child in self.main_sizer.GetChildren():
widget = child.GetWindow()
if isinstance(widget, gridlib.Grid):
self.main_sizer.Remove(widget)
grid = MyGrid(self, rows, cols)
self.main_sizer.Add(grid, 0, wx.ALL, 5)
self.grid_created = True
self.main_sizer.Layout()
########################################################################
class MyFrame(wx.Frame):
""""""
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, None, title="grids", size=(800, 600))
panel = MyPanel(self)
self.Show()
if __name__ == "__main__":
app = wx.App(False)
frame = MyFrame()
app.MainLoop()
You may only call the CreateGrid function once. if you want to change the size, you need to use the functions AppendCols, AppendRows, DeleteCols or DeleteRows.
def OnClick(self, event):
self.m_grid2.AppendCols(1)
self.m_grid2.AppendRows(1)
self.Layout()
Lokla

Categories

Resources