JustifiedCombobox, A subclass of ttk.Combobox that has adjustable pop-down list item justification

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
2
down vote

favorite












In an attempt to answer How to justify the characters in the drop-down list of a Combobx? I've come up with this code.



JustifiedCombobox justifies the pop-down list's items almost precisely after pop-down list's been first created & customized and then displayed. After the pop-down list's been created, setting self.justify value to a valid one will again, customize the justification almost right after the pop-down list's first been displayed:



try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
from tkinter import ttk
except:
import Tkinter as tk
import ttk


class JustifiedCombobox(ttk.Combobox):
"""
Creates a ttk.Combobox widget with its drop-down list items
justified with self.justify as late as possible.
"""

def __init__(self, master, *args, **kwargs):
ttk.Combobox.__init__(self, master, *args, **kwargs)
self.justify = 'center'


def _justify_popdown_list_text(self):
self._initial_bindtags = self.bindtags()
_bindtags = list(self._initial_bindtags)
_index_of_class_tag = _bindtags.index(self.winfo_class())
# This dummy tag needs to be unique per object, and also needs
# to be not equal to str(object)
self._dummy_tag = '_' + str(self)
_bindtags.insert(_index_of_class_tag + 1, self._dummy_tag)
self.bindtags(tuple(_bindtags))
_events_that_produce_popdown = tuple([ '<KeyPress-Down>',
'<ButtonPress-1>',
'<Shift-ButtonPress-1>',
'<Double-ButtonPress-1>',
'<Triple-ButtonPress-1>',
])
for _event_name in _events_that_produce_popdown:
self.bind_class(self._dummy_tag, _event_name,
self._initial_event_handle)


def _initial_event_handle(self, event):
_instate = str(self['state'])
if _instate != 'disabled':
if event.keysym == 'Down':
self._justify()
else:
_ = self.tk.eval(' identify element '.format(self,
event.x, event.y))
__ = self.tk.eval('string match *textarea '.format(_))
_is_click_in_entry = bool(int(__))
if (_instate == 'readonly') or (not _is_click_in_entry):
self._justify()


def _justify(self):
self.tk.eval('.popdown.f.l configure -justify '.format(self,
self.justify))
self.bindtags(self._initial_bindtags)


def __setattr__(self, name, value):
self.__dict__[name] = value
if name == 'justify':
self._justify_popdown_list_text()


def select_handle():
global a
_selected = a['values'][a.current()]
if _selected in ("left", "center", "right"):
a.justify = _selected


if __name__ == '__main__':
root = tk.Tk()
for s in ('normal', 'readonly', 'disabled'):
JustifiedCombobox(root, state=s, values=[1, 2, 3]).grid()
a = JustifiedCombobox(root, values=["Justify me!", "left", "center", "right"])
a.current(0)
a.grid()
a.bind("<<ComboboxSelected>>", lambda event: select_handle())
root.mainloop()


Review Concern(s):



  • My main concern is to code in an easy to read, efficient, and well-structured manner while still learning the language and concepts in computer science1 such as OOP. Feel free to mention the tiniest issue or improvement that comes to your mind, as I am a beginner and I probably need it.


  • I believe the code should run on both python 3.x and python 2.7, but I have only tested it for python 3.6.3. If the code doesn't work for those other versions, or it can work cross-version like I intended it to be but still could use improvements, please let me know.



1I haven't a degree in computer science or a very closely related subject.







share|improve this question



























    up vote
    2
    down vote

    favorite












    In an attempt to answer How to justify the characters in the drop-down list of a Combobx? I've come up with this code.



    JustifiedCombobox justifies the pop-down list's items almost precisely after pop-down list's been first created & customized and then displayed. After the pop-down list's been created, setting self.justify value to a valid one will again, customize the justification almost right after the pop-down list's first been displayed:



    try: # In order to be able to import tkinter for
    import tkinter as tk # either in python 2 or in python 3
    from tkinter import ttk
    except:
    import Tkinter as tk
    import ttk


    class JustifiedCombobox(ttk.Combobox):
    """
    Creates a ttk.Combobox widget with its drop-down list items
    justified with self.justify as late as possible.
    """

    def __init__(self, master, *args, **kwargs):
    ttk.Combobox.__init__(self, master, *args, **kwargs)
    self.justify = 'center'


    def _justify_popdown_list_text(self):
    self._initial_bindtags = self.bindtags()
    _bindtags = list(self._initial_bindtags)
    _index_of_class_tag = _bindtags.index(self.winfo_class())
    # This dummy tag needs to be unique per object, and also needs
    # to be not equal to str(object)
    self._dummy_tag = '_' + str(self)
    _bindtags.insert(_index_of_class_tag + 1, self._dummy_tag)
    self.bindtags(tuple(_bindtags))
    _events_that_produce_popdown = tuple([ '<KeyPress-Down>',
    '<ButtonPress-1>',
    '<Shift-ButtonPress-1>',
    '<Double-ButtonPress-1>',
    '<Triple-ButtonPress-1>',
    ])
    for _event_name in _events_that_produce_popdown:
    self.bind_class(self._dummy_tag, _event_name,
    self._initial_event_handle)


    def _initial_event_handle(self, event):
    _instate = str(self['state'])
    if _instate != 'disabled':
    if event.keysym == 'Down':
    self._justify()
    else:
    _ = self.tk.eval(' identify element '.format(self,
    event.x, event.y))
    __ = self.tk.eval('string match *textarea '.format(_))
    _is_click_in_entry = bool(int(__))
    if (_instate == 'readonly') or (not _is_click_in_entry):
    self._justify()


    def _justify(self):
    self.tk.eval('.popdown.f.l configure -justify '.format(self,
    self.justify))
    self.bindtags(self._initial_bindtags)


    def __setattr__(self, name, value):
    self.__dict__[name] = value
    if name == 'justify':
    self._justify_popdown_list_text()


    def select_handle():
    global a
    _selected = a['values'][a.current()]
    if _selected in ("left", "center", "right"):
    a.justify = _selected


    if __name__ == '__main__':
    root = tk.Tk()
    for s in ('normal', 'readonly', 'disabled'):
    JustifiedCombobox(root, state=s, values=[1, 2, 3]).grid()
    a = JustifiedCombobox(root, values=["Justify me!", "left", "center", "right"])
    a.current(0)
    a.grid()
    a.bind("<<ComboboxSelected>>", lambda event: select_handle())
    root.mainloop()


    Review Concern(s):



    • My main concern is to code in an easy to read, efficient, and well-structured manner while still learning the language and concepts in computer science1 such as OOP. Feel free to mention the tiniest issue or improvement that comes to your mind, as I am a beginner and I probably need it.


    • I believe the code should run on both python 3.x and python 2.7, but I have only tested it for python 3.6.3. If the code doesn't work for those other versions, or it can work cross-version like I intended it to be but still could use improvements, please let me know.



    1I haven't a degree in computer science or a very closely related subject.







    share|improve this question























      up vote
      2
      down vote

      favorite









      up vote
      2
      down vote

      favorite











      In an attempt to answer How to justify the characters in the drop-down list of a Combobx? I've come up with this code.



      JustifiedCombobox justifies the pop-down list's items almost precisely after pop-down list's been first created & customized and then displayed. After the pop-down list's been created, setting self.justify value to a valid one will again, customize the justification almost right after the pop-down list's first been displayed:



      try: # In order to be able to import tkinter for
      import tkinter as tk # either in python 2 or in python 3
      from tkinter import ttk
      except:
      import Tkinter as tk
      import ttk


      class JustifiedCombobox(ttk.Combobox):
      """
      Creates a ttk.Combobox widget with its drop-down list items
      justified with self.justify as late as possible.
      """

      def __init__(self, master, *args, **kwargs):
      ttk.Combobox.__init__(self, master, *args, **kwargs)
      self.justify = 'center'


      def _justify_popdown_list_text(self):
      self._initial_bindtags = self.bindtags()
      _bindtags = list(self._initial_bindtags)
      _index_of_class_tag = _bindtags.index(self.winfo_class())
      # This dummy tag needs to be unique per object, and also needs
      # to be not equal to str(object)
      self._dummy_tag = '_' + str(self)
      _bindtags.insert(_index_of_class_tag + 1, self._dummy_tag)
      self.bindtags(tuple(_bindtags))
      _events_that_produce_popdown = tuple([ '<KeyPress-Down>',
      '<ButtonPress-1>',
      '<Shift-ButtonPress-1>',
      '<Double-ButtonPress-1>',
      '<Triple-ButtonPress-1>',
      ])
      for _event_name in _events_that_produce_popdown:
      self.bind_class(self._dummy_tag, _event_name,
      self._initial_event_handle)


      def _initial_event_handle(self, event):
      _instate = str(self['state'])
      if _instate != 'disabled':
      if event.keysym == 'Down':
      self._justify()
      else:
      _ = self.tk.eval(' identify element '.format(self,
      event.x, event.y))
      __ = self.tk.eval('string match *textarea '.format(_))
      _is_click_in_entry = bool(int(__))
      if (_instate == 'readonly') or (not _is_click_in_entry):
      self._justify()


      def _justify(self):
      self.tk.eval('.popdown.f.l configure -justify '.format(self,
      self.justify))
      self.bindtags(self._initial_bindtags)


      def __setattr__(self, name, value):
      self.__dict__[name] = value
      if name == 'justify':
      self._justify_popdown_list_text()


      def select_handle():
      global a
      _selected = a['values'][a.current()]
      if _selected in ("left", "center", "right"):
      a.justify = _selected


      if __name__ == '__main__':
      root = tk.Tk()
      for s in ('normal', 'readonly', 'disabled'):
      JustifiedCombobox(root, state=s, values=[1, 2, 3]).grid()
      a = JustifiedCombobox(root, values=["Justify me!", "left", "center", "right"])
      a.current(0)
      a.grid()
      a.bind("<<ComboboxSelected>>", lambda event: select_handle())
      root.mainloop()


      Review Concern(s):



      • My main concern is to code in an easy to read, efficient, and well-structured manner while still learning the language and concepts in computer science1 such as OOP. Feel free to mention the tiniest issue or improvement that comes to your mind, as I am a beginner and I probably need it.


      • I believe the code should run on both python 3.x and python 2.7, but I have only tested it for python 3.6.3. If the code doesn't work for those other versions, or it can work cross-version like I intended it to be but still could use improvements, please let me know.



      1I haven't a degree in computer science or a very closely related subject.







      share|improve this question













      In an attempt to answer How to justify the characters in the drop-down list of a Combobx? I've come up with this code.



      JustifiedCombobox justifies the pop-down list's items almost precisely after pop-down list's been first created & customized and then displayed. After the pop-down list's been created, setting self.justify value to a valid one will again, customize the justification almost right after the pop-down list's first been displayed:



      try: # In order to be able to import tkinter for
      import tkinter as tk # either in python 2 or in python 3
      from tkinter import ttk
      except:
      import Tkinter as tk
      import ttk


      class JustifiedCombobox(ttk.Combobox):
      """
      Creates a ttk.Combobox widget with its drop-down list items
      justified with self.justify as late as possible.
      """

      def __init__(self, master, *args, **kwargs):
      ttk.Combobox.__init__(self, master, *args, **kwargs)
      self.justify = 'center'


      def _justify_popdown_list_text(self):
      self._initial_bindtags = self.bindtags()
      _bindtags = list(self._initial_bindtags)
      _index_of_class_tag = _bindtags.index(self.winfo_class())
      # This dummy tag needs to be unique per object, and also needs
      # to be not equal to str(object)
      self._dummy_tag = '_' + str(self)
      _bindtags.insert(_index_of_class_tag + 1, self._dummy_tag)
      self.bindtags(tuple(_bindtags))
      _events_that_produce_popdown = tuple([ '<KeyPress-Down>',
      '<ButtonPress-1>',
      '<Shift-ButtonPress-1>',
      '<Double-ButtonPress-1>',
      '<Triple-ButtonPress-1>',
      ])
      for _event_name in _events_that_produce_popdown:
      self.bind_class(self._dummy_tag, _event_name,
      self._initial_event_handle)


      def _initial_event_handle(self, event):
      _instate = str(self['state'])
      if _instate != 'disabled':
      if event.keysym == 'Down':
      self._justify()
      else:
      _ = self.tk.eval(' identify element '.format(self,
      event.x, event.y))
      __ = self.tk.eval('string match *textarea '.format(_))
      _is_click_in_entry = bool(int(__))
      if (_instate == 'readonly') or (not _is_click_in_entry):
      self._justify()


      def _justify(self):
      self.tk.eval('.popdown.f.l configure -justify '.format(self,
      self.justify))
      self.bindtags(self._initial_bindtags)


      def __setattr__(self, name, value):
      self.__dict__[name] = value
      if name == 'justify':
      self._justify_popdown_list_text()


      def select_handle():
      global a
      _selected = a['values'][a.current()]
      if _selected in ("left", "center", "right"):
      a.justify = _selected


      if __name__ == '__main__':
      root = tk.Tk()
      for s in ('normal', 'readonly', 'disabled'):
      JustifiedCombobox(root, state=s, values=[1, 2, 3]).grid()
      a = JustifiedCombobox(root, values=["Justify me!", "left", "center", "right"])
      a.current(0)
      a.grid()
      a.bind("<<ComboboxSelected>>", lambda event: select_handle())
      root.mainloop()


      Review Concern(s):



      • My main concern is to code in an easy to read, efficient, and well-structured manner while still learning the language and concepts in computer science1 such as OOP. Feel free to mention the tiniest issue or improvement that comes to your mind, as I am a beginner and I probably need it.


      • I believe the code should run on both python 3.x and python 2.7, but I have only tested it for python 3.6.3. If the code doesn't work for those other versions, or it can work cross-version like I intended it to be but still could use improvements, please let me know.



      1I haven't a degree in computer science or a very closely related subject.









      share|improve this question












      share|improve this question




      share|improve this question








      edited Jan 29 at 20:48
























      asked Jan 29 at 17:39









      Nae

      25019




      25019

























          active

          oldest

          votes











          Your Answer




          StackExchange.ifUsing("editor", function ()
          return StackExchange.using("mathjaxEditing", function ()
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          );
          );
          , "mathjax-editing");

          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          convertImagesToLinks: false,
          noModals: false,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );








           

          draft saved


          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f186271%2fjustifiedcombobox-a-subclass-of-ttk-combobox-that-has-adjustable-pop-down-list%23new-answer', 'question_page');

          );

          Post as a guest



































          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes










           

          draft saved


          draft discarded


























           


          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f186271%2fjustifiedcombobox-a-subclass-of-ttk-combobox-that-has-adjustable-pop-down-list%23new-answer', 'question_page');

          );

          Post as a guest













































































          Popular posts from this blog

          Python Lists

          Aion

          JavaScript Array Iteration Methods