pythonfontswxpythonpython-3.7wxstyledtextctrl

Change the font in a wxPython StyledTextCtrl


I have been coding with wxPython and have run into a problem. I've created a FontDialog Function that also changes the font. The problem is that I am unable to change the font. In tkinter, you can widget.config(font=font) and the font changes instantly. I have been unable to figure out how to do that on a wxPython StyledTextCtrl. Any help would be appreciated. Here is my current code:

Define the widget:

self.control = wx.stc.StyledTextCtrl(self, style=wx.TE_MULTILINE)
self.control.SetMarginWidth(1, 0)
self.control.SetScrollWidth(wx.stc.STC_CACHE_CARET)
self.CreateStatusBar()

Call the font function:

self._font = self.formatmenu.Append(wx.ID_SELECT_FONT, 'Font...', 'Change the font displayed in the editor')
self.Bind(wx.EVT_MENU, self.font_func, self._font)

The function:

def font_func(self, event):
    dialog = wx.FontDialog()
    if dialog.ShowModal() == wx.ID_CANCEL:
        return
    font = wx.Font(dialog.GetFont())
    self.control.StyleSetFont(0, font=font) # Here is my error - nothing happens.

Thanks, Legorooj.


Solution

  • The way that you are using FontDialog I think is simply returning the current font.
    You need to access the GetFontData function, like so:

    >>> dlg = wx.FontDialog(None)
    >>> if dlg.ShowModal()==wx.ID_OK:
    ...  font = dlg.GetFontData().GetChosenFont()
    ...  print(font.GetFaceName())
    ... 
    Times New Roman