Skip to content Skip to sidebar Skip to footer

Problems With Superscript Using Python Tkinter Canvas

I am trying to use canvas.create_text(...) to add text to a drawing. I have been somewhat successful using unicode in the following way: mytext = u'U\u2076' #U^6 canvas.create_te

Solution 1:

Your problem comes from the handling of Unicode on your platform and in your fonts. As explained on wikipedia : superscript 1,2 and 3 where previously handled in Latin-1 and thus get different support in fonts.

I did not notice fixed size issue, but on most fonts (on Linux and MacOS), 1,2,3 are not properly aligned with 4-9.

My advice would be to select a font that match your need (you may look at DejaVu family, which provide libre high quality fonts).

Here is a litte application to illustrate the handling of superscripts with different fonts or size.

from Tkinter import *
import tkFont

master = Tk()

canvas = Canvas(master, width=600, height=150)
canvas.grid(row=0, column=0, columnspan=2, sticky=W+N+E+S)

list = Listbox(master)
for f insorted(tkFont.families()):
    list.insert(END, f)

list.grid(row=1, column=0)

font_size= IntVar()
ruler = Scale(master, orient=HORIZONTAL, from_=1, to=200, variable=font_size)
ruler.grid(row=1, column=1, sticky=W+E)


deffont_changed(*args):
    sel = list.curselection()
    font_name = list.get(sel[0]) iflen(sel) > 0else"Times"
    canvas.itemconfig(text_item, font=(font_name,font_size.get()))
    #force redrawing of the whole Canvas# dirty rectangle of text items has bug with "superscript" character
    canvas.event_generate("<Configure>")

defdraw():
    supernumber_exception={1:u'\u00b9', 2:u'\u00b2', 3:u'\u00b3'}
    mytext =""for i inrange(10):
        mytext += u'U'+ (supernumber_exception[i] if i in supernumber_exception else unichr(8304+i))+" "return canvas.create_text(50, 50,text = mytext, anchor=NW)

text_item = draw()

list.bind("<<ListboxSelect>>", font_changed)

font_size.trace("w", font_changed)
font_size.set(30)

master.grid_columnconfigure(0, weight=0)
master.grid_columnconfigure(1, weight=1)
master.grid_rowconfigure(0, weight=1)
master.grid_rowconfigure(1, weight=0)

master.mainloop()

Post a Comment for "Problems With Superscript Using Python Tkinter Canvas"