Search code examples
pythontkinterbuttoncanvasconfigure

configure button on canvas in python


I'm working on GUI project and I'm trying to configure a button color and text but it gives me an error.. here is a sample of my code:

from tkinter import*
from tkinter import ttk
#root
root = Tk()
root.geometry('640x520')

#Canvas 
myCanvas = Canvas(root, width=350, height=300, bd=0, highlightthickness=0)
myCanvas.pack(fill='both', expand=True)
def qu1():
    global myCanvas
    myCanvas.itemconfig(Q1,bg='green',text= 'Done')
Q1 = Button(root, width=15, height=10, bg='#F3C4B7',fg='white', text='1', command=qu1)
myCanvas.create_window(10,10, anchor='nw', window=Q1)
root.mainloop()

it gives me this error:

line 12, in qu1
    myCanvas.itemconfig(Q1,bg='green',text= 'Done')
_tkinter.TclError: invalid boolean operator in tag search expression

Solution

  • Already stated:

    itemconfig applies to Canvas objects

    You can do:

    from tkinter import*
    root = Tk()
    root.geometry('640x520')
    myCanvas = Canvas(root, width=350, height=300, bd=0, highlightthickness=0)
    myCanvas.pack(fill='both', expand=True)
    buttonBG = myCanvas.create_rectangle(0, 0, 100, 30, fill="grey40", outline="grey60")
    buttonTXT = myCanvas.create_text(50, 15, text="click")
    def qu1(event):
        myCanvas.itemconfig(buttonBG, fill='red')
        myCanvas.itemconfig(buttonTXT, fill='white')
    myCanvas.tag_bind(buttonBG, "<Button-1>", qu1)
    myCanvas.tag_bind(buttonTXT, "<Button-1>", qu1)
    root.mainloop()
    

    Or change the button itself:

    from tkinter import*
    root = Tk()
    root.geometry('640x520')
    myCanvas = Canvas(root, width=350, height=300, bd=0, highlightthickness=0)
    myCanvas.pack(fill='both', expand=True)
    def qu1():
        Q1.configure(bg="#234")
    Q1 = Button(root, width=15, height=10, bg='#F3C4B7',fg='white', text='1', command=qu1)
    myCanvas.create_window(10,10, anchor='nw', window=Q1)
    root.mainloop()