nickvans nickvans - 1 month ago 7
Python Question

How do I programmatically set the checked state of an Python XRC MenuItem?

I have a menu defined using XRC like this:

<object class="wxMenuItem" name="MenuItem_ShowTooltips">
<label>Show tooltips</label>
<checkable>1</checkable>
</object>


which I initialize in my app from it's parent frame like this

self.frame = self.res.LoadFrame(None, 'MainFrame')


When my app starts I check a user preferences file to get initial values (a boolean in this case) and want to check or uncheck the MenuItem based on that parameter. With a normal wx control I could use something like

self.MenuItem_ShowTooltips.Check(self.UserPreferences['ShowTooltips'])


How can I get a handle on the XRC created MenuItem_ShowTooltips control?

Answer

Well, after a couple days of fiddling, I found my answer. In case it helps anyone else, or in case I forget and end up back on StackOverflow to find the answer again, here it is.

To get a handle on the menu item you have to use GetMenuBar() method of the wx window.

self.MenuItem_ShowTooltips = self.TopWindow.GetMenuBar().FindItemById(xrc.XRCID('MenuItem_ShowTooltips'))

Once you have a handle on that you can set it's checked state like this

self.MenuItem_ShowTooltips.Check(self.UserPreferences['ShowTooltips'])

And you bind it to an event like this

self.frame.Bind(wx.EVT_MENU, self.SaveUserPrefs, id=xrc.XRCID('MenuItem_ShowTooltips'))