How do I use a standard color picker

It would be useful if the user was allowed to select an arbitrary color in the sketch dialog. For that purpose, we can use the standard wx.ColourDialog provided by wxPython. Use of this dialog is similar to the file dialog. The constructor takes only a parent and an optional data attribute. The data attribute is an instance of wx.ColourData, storing some data associated with the dialog such as the user-chosen color, and the list of custom colors. Using the data attribute allows you to keep the custom colors consistent from one usage to the next.

Using the color dialog in the sketch application requires the addition of a menu item, and a pretty straightforward handler method. Listing 6.7 shows the additions to the code.

Listing 6.7 Changes to the SketchFrame to display the color dialog def menuData(self):

("&New", "New Sketch file", self.OnNew), ("&Open", "Open sketch file", self.OnOpen), ("&Save", "Save sketch file", self.OnSave), ("", "", ""), ("&Color", (

("&Black", "", self.OnColor, wx.ITEM_RADIO), ("&Red", "", self.OnColor, wx.ITEM_RADIO), ("&Green", "", self.OnColor, wx.ITEM_RADIO), ("SBlue", "", self.OnColor, wx.ITEM_RADIO), ("&Other...", "", self.OnOtherColor, wx.ITEM_RADIO))), ("", "", ""),

("&Quit", "Quit", self.OnCloseWindow)))]

def OnOtherColor(self, event): dlg = wx.ColourDialog(self)

dlg.GetColourData().SetChooseFull(True) <— Creating color data object if dlg.ShowModal() == wx.ID_OK:

self.sketch.SetColor(dlg.GetColourData().GetColour()) <—, dlg Destroy() Setting color from user input |

We've done two things with the color dialog that may not be immediately obvious. The SetChooseFull() method of the color data instance tells the dialog to display with the full palette, including the custom color information. After the dialog is closed, we grab the color data again to get the color. The color data is returned as a wx.Color instance and is suitable for passing back to the sketch to set the color.

Was this article helpful?

0 0

Post a comment