Search code examples
pythonunicodetkinternotation

displaying subscript/superscripts in python tkinter listbox with unicode


I need to display some values with subscripts/superscripts in a Tkinter Listbox in Python.

I have managed to get output to display with hardcoded values like so:

 listbox.insert(i, (u"C\u2076"))

This displays: C6

That is the desired output I want; however, the value of 6 needs to be taken from a variable. I can't figure out how to concatenate a variable onto the u"C\u207" portion. If I try building it using a string, it has an escape character and displays like "C\2076", so that didn't work.

How else can I do this?


Solution

  • I managed to figure it out for myself. The comment above was helpful, but I still needed a way to concatenate the unicode characters because I was building a much larger list of characters.

    To concatenate the unicode characters, I found pythons built in unicode function.

    I returned the superscript like the above linked thread demonstrated:

    def get_superscript_unicode(n):
        codes = {
            1 : u"\u00B9",
            2 : u"\u00B2",
            3 : u"\u00B3",
            4 : u"\u2074",
            5 : u"\u2075",
            6 : u"\u2076",
            7 : u"\u2077"
        }
        return unicode(codes[n])
    

    To concatenate multiple unicode returns, I did something similar to this:

    for item in list:
        s += unicode(get_superscript_unicode(n)) + unicode(other text)
    return unicode(s)
    

    I probably have one too many calls to unicode there. I kind of quickly took out the relevant pieces of a much more complicated string being built.