python 中 canvas 上的配置按钮

configure button on canvas in python

我正在处理 GUI 项目,我正在尝试配置按钮颜色和文本,但它给了我一个错误.. 这是我的代码示例:

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()

它给我这个错误:

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

已说明:

itemconfig applies to Canvas objects

你可以这样做:

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()

或更改按钮本身:

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()