logo
down
shadow

Wxpython - convert static positioning to sizer


Wxpython - convert static positioning to sizer

By : Hoang The
Date : November 22 2020, 10:38 AM
this one helps. I have been using static positioning in wxpython for a while now but need to switch to using sizers, but I just can't get the hang of it. Below is a cut down version of my application using static positioning. could someone give me some pointers as to how I go about converting this layout to using sizers please. I will attach a screen grab also: , It's still a bit fiddly, but here it is with BoxSizer's:
code :
import wx

class MainWindow(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(900, 600) )      

        SubmissionsPanel(self)
        self.Show()

class SubmissionsPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

        #Create some sizers:
        main_sizer = wx.BoxSizer(wx.VERTICAL)
        top_row_sizer = wx.BoxSizer(wx.HORIZONTAL);
        radio_static_box = wx.StaticBox(self, label='') #You have to add this widget to parent BEFORE
                                                        #contained widgets otherwise buttons won't operate.
        radio_static_box_sizer = wx.StaticBoxSizer(radio_static_box, wx.HORIZONTAL)

        job_static_box = wx.StaticBox(self, label='')  #You have to add this widget to parent BEFORE 
                                                       #contained widgets otherwise buttons won't operate.
        job_static_box_sizer = wx.StaticBoxSizer(job_static_box, wx.HORIZONTAL)


        '''
        radio_labels = ['Verify Mode', 'Upload Mode']
        self.radio_box = wx.RadioBox(
                self, -1, "", 
                choices=radio_labels,
        )
        '''
        #I couldn't get the radio buttons inside a RadioBox to line up vertically
        #with the checkbox, so I did the following:
        radio1 = wx.RadioButton(self, label='Verify Mode', style=wx.RB_GROUP)
        radio2 = wx.RadioButton(self, label='Upload Mode')
        radio1.Bind(wx.EVT_RADIOBUTTON, self.on_radio_click)
        radio2.Bind(wx.EVT_RADIOBUTTON, self.on_radio_click)

        radio_static_box_sizer.Add(radio1, flag=wx.BOTTOM, border=4) #To make outline line up with the outline of checkbox,txtctrl
        radio_static_box_sizer.Add(radio2, flag=wx.LEFT, border=10)

        top_row_sizer.Add(radio_static_box_sizer, flag=wx.LEFT, border=10)


        #Create Job Title widgets:
        self.check_box = wx.CheckBox(self, label="Job Title")
        self.check_box.SetValue(False)
        self.check_box.Bind(wx.EVT_CHECKBOX, self.ShowOrHideTVTitle)

        self.txtTitle = wx.TextCtrl(self, style=wx.SUNKEN_BORDER, value="Enter job title here...", size=(200, -1))
        self.txtTitle.Show(False)

        job_static_box_sizer.Add(self.check_box, flag=wx.LEFT, border=10)
        job_static_box_sizer.Add(self.txtTitle, flag=wx.RESERVE_SPACE_EVEN_IF_HIDDEN | wx.LEFT, border=10)

        top_row_sizer.Add(job_static_box_sizer, flag=wx.LEFT, border=10);

        main_sizer.Add(top_row_sizer);
        main_sizer.Add((-1, 20))  #Add 20 pixels of vertical space

        #Drag n Drop widgets:
        drag_drop_text = wx.StaticText(self, -1, 'Drag n Drop itmsp folder')
        main_sizer.Add(drag_drop_text, flag=wx.LEFT, border=10)
        main_sizer.Add((-1, 3))  #Add 3 pixels of vertical space

        third_row_sizer = wx.BoxSizer(wx.HORIZONTAL);
        self.tc_files = wx.TextCtrl(self, size=(375, 25))
        self.buttonGo = wx.Button(self, label='Submit')
        third_row_sizer.Add(self.tc_files, flag=wx.LEFT, border=10)
        third_row_sizer.Add(self.buttonGo, flag=wx.LEFT, border=10)
        main_sizer.Add(third_row_sizer)

        #Create ListCtrl:
        self.index = 0        
        self.log_text22 = wx.ListCtrl(self,size=(800,275),
                         style=wx.LC_REPORT | wx.BORDER_SUNKEN | wx.LC_SINGLE_SEL | wx.LC_VRULES | wx.LC_HRULES)

        font = wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)
        self.log_text22.SetFont(font)

        self.log_text22.InsertColumn(1, 'Job ID', width=50, format=wx.LIST_FORMAT_CENTRE)
        self.log_text22.InsertColumn(2, 'Mode  ', width=50, format=wx.LIST_FORMAT_CENTRE)
        self.log_text22.InsertColumn(3, 'Title', width=183)
        self.log_text22.InsertColumn(4, 'Package', width=227)
        self.log_text22.InsertColumn(5, 'Submitted By', width=100)
        self.log_text22.InsertColumn(6, 'Sumbit Time', width=85)
        self.log_text22.InsertColumn(7, 'Process', width=50, format=wx.LIST_FORMAT_CENTRE)
        self.log_text22.InsertColumn(8, 'Status  ', width=50, format=wx.LIST_FORMAT_CENTRE)

        main_sizer.Add((-1, 20)) #Add 20px of vertical space
        list_sizer = wx.BoxSizer(wx.VERTICAL)
        list_sizer.Add(self.log_text22, flag=wx.LEFT, border=10)
        main_sizer.Add(list_sizer)

        #Create Quit button:
        list_sizer.Add((-1, 10))  #Add 15px of vertical space
        self.buttonClose = wx.Button(self, -1, "Quit Application")
        list_sizer.Add(self.buttonClose, flag=wx.ALIGN_CENTER | wx.TOP | wx.LEFT, border=10)

        self.SetSizer(main_sizer)


    def on_radio_click(self, evt):
        print "You clicked?"

    def ShowOrHideTVTitle(self, evt):
        element = evt.GetEventObject()
        isChecked = element.GetValue()

        if isChecked:
            self.txtTitle.Show(True)
            self.txtTitle.SetFocus()
        else:
            self.txtTitle.Show(False)
            self.tc_files.SetFocus()

    def OnSubmit(self):
        pass

    def OnClose(self):
        pass

    def showLogFile(self):
        pass

    def right_click(self):
        pass

app = wx.App(redirect=False) ##Instead of seeing just a window flash, show errors in terminal.
MainWindow(None, -1, 'Test App')
app.MainLoop()


Share : facebook icon twitter icon
wxPython: Can a wx.PyControl contain a wx.Sizer?

wxPython: Can a wx.PyControl contain a wx.Sizer?


By : Marc Babin
Date : March 29 2020, 07:55 AM
Hope that helps Yes, it can. You just need to call Layout() to tell the sizer to recalculate/layout its children.
code :
import wx

class Frame(wx.Frame):
  def __init__(self):
    wx.Frame.__init__(self, None)
    blah  = CustomWidget(self)
    self.Show(True)

class CustomWidget(wx.PyControl):
  def __init__(self, parent):
    wx.PyControl.__init__(self, parent=parent)
    text = wx.TextCtrl(parent=self)
    spin = wx.SpinButton(parent=self, style=wx.SP_VERTICAL)
    sizer = wx.GridBagSizer()
    self.layout(text, spin, sizer)
    self.OnInit(text, sizer)

  def OnInit(self, text, sizer):
    text.SetValue(u"0.000")

  def layout(self, text, spin, sizer):
    self.SetSizer(sizer)
    sizer.Add(text, pos=(0, 0), flag=wx.ALIGN_CENTER)
    sizer.Add(spin, pos=(0, 1), flag=wx.ALIGN_CENTER)
    self.Fit()
    self.Layout()
    self.CenterOnParent()

app = wx.App()
f = Frame()
app.MainLoop()
wxPython: How to get sizer from wx.StaticText?

wxPython: How to get sizer from wx.StaticText?


By : Chris Cordova
Date : March 29 2020, 07:55 AM
it helps some times If the sizer has children, then GetChildren does return a list of widgets. I've done it many times with wxPython 2.8. I don't remember anyone mentioning it was different in 2.9 or Phoenix, so I'm guessing it's not. Can you tell us which OS and wxPython version you're using?
If you want to know how to get an arbitrary sizer, you might try GetContainingSizer or use the Widget Inspection Tool
code :
import wx

########################################################################
class MyApp(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title="Example")
        panel = wx.Panel(self)

        lbl = wx.StaticText(panel, label="I'm a label!")
        txt = wx.TextCtrl(panel, value="blah blah")
        btn = wx.Button(panel, label="Clear")
        btn.Bind(wx.EVT_BUTTON, self.onClear)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(lbl, 0, wx.ALL, 5)
        self.sizer.Add(txt, 0, wx.ALL, 5)
        self.sizer.Add(btn, 0, wx.ALL, 5)

        panel.SetSizer(self.sizer)

    #----------------------------------------------------------------------
    def onClear(self, event):
        """"""
        children = self.sizer.GetChildren()

        for child in children:
            widget = child.GetWindow()
            print widget
            if isinstance(widget, wx.TextCtrl):
                widget.Clear()

if __name__ == "__main__":
    app = wx.App(False)
    frame = MyApp()
    frame.Show()
    app.MainLoop()
wxPython — StaticBox Sizer resizing Static Boxes

wxPython — StaticBox Sizer resizing Static Boxes


By : ickle_matt
Date : March 29 2020, 07:55 AM
This might help you Adding the text widget to 6 different sizers is never a good idea. I recommend creating a new instance of StaticText for each sizer. The reason for the overlap is that you need to increase your vgap when using StaticBoxsizers.
Here's an updated version of the code:
code :
import wx

def createBoxes():
    outVSizer = wx.BoxSizer(wx.VERTICAL)
    outHSizer = wx.BoxSizer(wx.HORIZONTAL)
    outVSizer.AddStretchSpacer(1)
    outHSizer.AddStretchSpacer(1)
    sizer = wx.FlexGridSizer(rows=3, cols=3, vgap=55, hgap=20)

    box = {}
    boxSizer = {}
    #text = wx.StaticText(panel, wx.ID_ANY, "This is a test")
    for i in range(6):
        box[i] = wx.StaticBox(panel, wx.ID_ANY, "testBox", size=(0,100))
        text = wx.StaticText(panel, wx.ID_ANY, "This is a test")
        boxSizer[i] = wx.StaticBoxSizer(box[i], wx.VERTICAL)
        boxSizer[i].Add(text, proportion = 1, flag=wx.ALIGN_CENTER)
        sizer.Add(boxSizer[i], flag=wx.EXPAND)
    sizer.AddGrowableCol(0,1)
    sizer.AddGrowableCol(1,1)
    sizer.AddGrowableCol(2,1)

    outHSizer.Add(sizer, flag=wx.EXPAND, proportion=15)
    outHSizer.AddStretchSpacer(1)
    outVSizer.Add(outHSizer, flag=wx.EXPAND, proportion=15)
    panel.SetSizer(outVSizer)

app = wx.App()
frame = wx.Frame(None, size=(500,500))
panel = wx.Panel(frame)
createBoxes()
frame.Show()
app.MainLoop()
wxPython using a sizer with panels

wxPython using a sizer with panels


By : user3398597
Date : March 29 2020, 07:55 AM
Any of those help First of all, you don't give any size to your HUDPanel, so I'm not sure how do you expect it to appear.
Second, you're recursively calling update all the time (well every 15ms), which is most definitely a bad idea as this will consume close to 100% of (one) CPU and may prevent your application from dispatching other events.
wxpython set sizer background

wxpython set sizer background


By : Pwelpatate
Date : March 29 2020, 07:55 AM
this one helps. I just use panels for this sort of thing. You can set the color of the panel several different ways: you can use a named color, a wx.Color object, a predefined wx.Color object like wx.RED or a tuple of 3 integers.
Here's a simple example:
code :
import wx

class MyPanel(wx.Panel):

    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

        self.SetBackgroundColour('white')

        main_sizer = wx.BoxSizer(wx.VERTICAL)
        for number in range(5):
            btn = wx.Button(self, label='Button {}'.format(number))
            main_sizer.Add(btn, 0, wx.ALL, 5)

        self.SetSizer(main_sizer)


class MyFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, title='Background colors')
        panel = MyPanel(self)
        self.Show()

if __name__ == '__main__':
    app = wx.App(False)
    frame = MyFrame()
    app.MainLoop()
Related Posts Related Posts :
  • Testing logging output with pytest
  • How do I change my default working directory for Python (Anaconda) on VSCode?
  • .lower() for x in list, not working, but works in another scenario
  • Program gives error "List indices must not be string"
  • pyqt: Memory Usage
  • Confused about classes in Learn Python the Hard Way ex43?
  • Extracting unrecognized information from many CSV files
  • How do I connect to Postgresql server from Python?
  • Append rows to a pandas DataFrame without making a new copy
  • Scrapy: Importing a package from the project that's not in the same directory
  • launching Excel application using Python to view the CSV file , but CSV file is opening in read mode and cant view the d
  • Making a list in user-defined functions
  • Pyserial microcontroller to host communication
  • Plotting a line in between subplots
  • function not returning value. Error "NameError: name 'urlss' is not defined"
  • How to perform cartesian product with Tensorflow?
  • Multiple independent random number streams from single seed
  • I Need a simple and short python3 code that count secounds in a background process
  • No module named constants
  • from django 1.4 to django 1.5- argument 'verify_exists' what s replacement?
  • Slash replacement inside a raw string
  • Reordering columns/rows of a pivot_table?
  • MySQLdb.cursors.Cursor.execute does not work
  • Python module being reimported when imported at different places
  • Is the Session object from Python's Requests library thread safe?
  • Python Regex: Finding First and Last Names
  • Order by selection in List view of OpenERP 7.0
  • Reading input values in ipython notebook
  • List of dictionaries - how to read a specific value in a dictionary
  • writing os.system output to file
  • Create dictionary from points list and multiple attribute lists
  • How to write a table line by line with for loop
  • Map projection and forced interpolation
  • Django FBV's "render_to_response" equivalent in Class-Based-View?
  • Paramiko raises "SFTPError: Garbage packet received"
  • python pandas operations on columns
  • python list appending is not working
  • Speeding up matplotlib scatter plots
  • For each element of the list find closest date from a different list
  • How to prepend new rows at the beginning of an existing csv file?
  • how to make database robust to process kills with sqlite postgress and sqlalchemy?
  • finding a set of ranges that a number fall in
  • New line in python print() function
  • How to clear os.environ value for only one Variable in Python
  • Why does python append a modulo(%) operator to the end of a newly opened file?
  • recursive function or non-recursive that doesnt use 2 ** approach
  • Extract floats from a String using regular expression
  • How to solve: ImportError: No module named django.core.wsgi in Apache2 log?
  • What's the most concise way to include multiple statements in a Python switch case?
  • python xml pretty print not working
  • Can we use NumPy in writing a website?
  • Called bashscript doesn't start up GNU screen session
  • Reading fortran direct access data and writing formatted data - faster with python than with fortran?
  • Language supporting nested definition of functions
  • Find elements which exists in the most of the lists
  • Templating library in node.js similar to Jinja2 in Python?
  • Python Syntax Error, 'break' is outside the loop
  • Replacing spaces with hyphens
  • How to open a csv file in Microsoft Excel in Python?
  • ModuleNotFoundError: No module named 'users'
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org