Problems with superscript using Python tkinter canvas

萝らか妹 提交于 2019-12-24 09:57:24

问题


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_text(xPos,yPos,text = mytext, font = ("Times","30")
canvas.pack()

It works, but when increasing the font size, superscripts 4,5,6,7,8,9,0 do not increase in size. Only 1,2,3 work. I'm assuming it's the same for subscripts. Also, when I save the canvas as a postscript, the problem superscripts are gone...but when I print out that saved image, the superscripts return.

Am I just completely wrong with my approach? I'm just looking to make this work so any help would be greatly appreciated. Thank you.


回答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 in sorted(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)


def font_changed(*args):
    sel = list.curselection()
    font_name = list.get(sel[0]) if len(sel) > 0 else "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>")

def draw():
    supernumber_exception={1:u'\u00b9', 2:u'\u00b2', 3:u'\u00b3'}
    mytext =""
    for i in range(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()


来源:https://stackoverflow.com/questions/10098100/problems-with-superscript-using-python-tkinter-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!