Autosize ListBox to fit widest item

Here’s the problem.

I want to create a ListBox of items down the far right of the screen. I want the frame to be sized to fit the widest item in the ListBox. So far nothing I have tried seems to work. Do you have any suggestions?

Keep in mind that replying “add a sizer to the frame” won’t help me because of the large permutation of options and sizers available. I’ve tried several with no luck. If you have a suggestion please be specific.

import wx

class MyApp(wx.App):

    def OnInit(self):
        self.Init()
        frame = Frame()
        return True

class Frame(wx.Frame):

    def __init__(self,parent=None,id=-1):

        wx.Frame.__init__(self, None, -1, 'Show Groups')

        self.Bind(wx.EVT_CLOSE,self.OnExit,self)

        screenw, screenh = wx.DisplaySize()

        self.panel = Panel(self)          
        self.SetSize(-1,screenh - 30)
        self.Move(screenw-self.Size.width,0)
        self.Fit()

        self.Show()

    def OnExit(self,event):

        self.Destroy()

class Panel(wx.Panel):

    def __init__(self, parent):

        wx.Panel.__init__(self, parent, -1)

        text  = "Brewster had dwelt upon the regenerationthisisaverylongword of the Hydra, the small fresh water worm"
        words = text.split()

        sizer = wx.BoxSizer(wx.VERTICAL)

        self.listbox = wx.ListBox(self, -1, choices=words, style=wx.LB_SINGLE)

        sizer.Add(self.listbox, 1, wx.ALIGN_LEFT | wx.EXPAND, 0)
        self.SetSizerAndFit(sizer)

app = wx.App(False)
frame = Frame()
app.MainLoop()

It appears to work on Linux python3.6, wxPython 4.0.7???

Johnf

It’s also working on Windows, but you should describe your problem and platform.
Is the problem that the frame is wider than necessary?
I’ve just tried. On Windows the default size for a frame seems to be 400x250 and so the width will be at least 400. Maybe there are options to make the frame shrink.
A dialog would shrink to the required size.

Use something like self.SetSize(self.panel.listbox.GetBestSize()[0], screenh - 30) to shrink the frame.

For a better result, check wx.SystemMetric.

Regards,
Dietmar

self.SetSize(self.panel.listbox.GetBestSize()[0], screenh - 30)

was just what I needed.I should have specified Windows 10. Thanks.