Question

I’m creating a wx.Dialog subclass and I’m a little confused about how the dialog’s DefaultItem property is supposed to work. I’m running on OS X. I put together this short example:

import wx

class DialogTest(wx.Dialog):
    def __init__(self, parent):
        wx.Dialog.__init__(self, parent)

        # text_entry = wx.TextCtrl(self, wx.NewId(), '')

        button_sizer = wx.StdDialogButtonSizer()

        ok_button = wx.Button(self, wx.ID_OK, 'OK')
        button_sizer.SetAffirmativeButton(ok_button)
        self.SetDefaultItem(ok_button)

        cancel_button = wx.Button(self, wx.ID_CANCEL, 'Cancel')
        button_sizer.SetCancelButton(cancel_button)

        button_sizer.Realize()

        outer_sizer = wx.BoxSizer(wx.VERTICAL)
        # outer_sizer.Add(text_entry)
        outer_sizer.Add((100, 100))
        outer_sizer.Add(button_sizer, flag=wx.ALIGN_RIGHT | wx.BOTTOM, border=6)

        self.SetSizer(outer_sizer)
        outer_sizer.Fit(self)


if __name__ == '__main__':
    app = wx.App(False)
    DialogTest(None).ShowModal()
    app.MainLoop()

This displays a simple dialog with “OK” and “Cancel” buttons. If you uncomment the two commented-out lines there will also be a text box. I have two questions:

  1. If I uncomment the TextCtrl lines then I can activate the OK button by pressing Return. If those lines are commented out, though, pressing Return doesn’t “click” OK. (I tried clicking within the window first, to make sure that this wasn’t some kind of focus problem, but that didn’t change anything.) Why can’t I use Return to hit the OK button without the text field in place? (Hitting Esc activates the Cancel button regardless of whether the text field is there.)

  2. Why doesn’t the OK button have the pulsating blue “default button” appearance? It should look like this one:

Screenshot of standard OS X buttons, showing a normal Cancel button and an OK button that has the glowing blue “default” appearance.

Was it helpful?

Solution

Instead of self.SetDefaultItem(ok_button) use ok_button.SetDefault(). The first just informs the dialog which will be the default button, but doesn't tell the button anything. The latter tells the button to be the default and then it tells the parent.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top