Search code examples
pythontkinter

Creating a bulleted list on a label widget using python tkinter


Is there any way to create a hanging indented list using the tkinter label widget? Note: Using propper standard bullets not * or -.


Solution

  • you can use unicode code points, as a rough implementation:

    try:
        import tkinter as tk
    except ImportError:
        import Tkinter as tk
    
    class BulletLabel(tk.Label):
        def __init__(self, master, *args, **kwargs):
            text = kwargs.pop('text', '')
            kwargs['text'] = self.bulletise(text)
            tk.Label.__init__(self, master, *args, **kwargs)
    
        def bulletise(self, text):
            if len(text) == 0: # no text so no bullets
                return ''
            lines = text.split('\n')
            parts = []
            for line in lines: # for each line
                parts.extend(['\u2022', line, '\n']) # prepend bullet and re append newline removed by split
            return ''.join(parts)
    
        def configure(self, *args, **kwargs):
            text = kwargs.pop('text', '')
            if text != '':
                kwargs['text'] = self.bulletise(text)
            tk.Label.configure(*args, **kwargs)
    
    
    root = tk.Tk()
    
    blabel = BulletLabel(root, text='one\ntwo\nthree')
    blabel.pack()
    
    root.mainloop()