Search code examples
pythoncanvasfontslistboxtkinter

Changing font style in canvas is giving me a error when font is not one word python Tkinter


I have a Toplevel() window that has the a listbox widget of fonts and once the user clicks a item in the list a canvas widget that is in the same window rewrites what words are in it (Hi how are you?) with the font that the user chose. It works fine if the font is one word. But if the font is a font like (Comic Sans MS) How it has spaces in it I get a error: Here is the error:

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in __call__
return self.func(*args)
File "C:\Users\Christian\Desktop\Basic Text - Copy.pyw", line 292, in changefont
canvas.create_text(150,20, fill="black", font=st + " 11 italic normal", text="Hi how are you?")
File "C:\Python27\lib\lib-tk\Tkinter.py", line 2294, in create_text
return self._create('text', args, kw)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 2270, in _create
*(args + self._options(cnf, kw))))
TclError: expected integer but got "Sans"

Here is the code:

def font(self):
    font = "Arial"
    style = "Regular"
    fontwindow = Toplevel()
    fontwindow.title("Font settings")
    fontwindow.resizable(0,0)

    fontfr5 = Frame(fontwindow,bd="2" ,padx=10,pady=10,width=300,height=60)
    fontfr5.pack(side=LEFT)
    label4= Label(fontfr5)
    label4["text"]="Example: "
    label4.pack(side=LEFT)
    canvas = Canvas(fontfr5,bg="white",width=300,height=40)
    canvas.pack(side=LEFT)
    canvas.create_text(150,20, fill="black", font="Arial 11 normal", text="Hi how are you?")

    def changefont(event): --Here is the function for the font change
        canvas.delete(ALL)
        selected = fontlist.get(fontlist.curselection())
        st = "".join(selected)
        findfont.delete(0,END)
        findfont.insert(0,st)
        canvas.create_text(150,20, fill="black", font=st + " 11 italic normal", text="Hi how are you?")

    def changestyle(event):
        selected = stylelist.get(stylelist.curselection())
        style = selected
        findstyle.delete(0,END)
        findstyle.insert(0,selected)

    fontlist.bind("<<ListboxSelect>>", changefont)
    stylelist.bind("<<ListboxSelect>>", changestyle)

I have used "".join(selected) to join it into one string if it is more than one word because it is in index's. But how can I get it to work with fonts that are more than one word?


Solution

  • Use tuple

    font=('Comic Sans MS', 12, 'bold italic')