绑定/事件给出错误' int'对象没有属性' bind'

时间:2015-03-19 23:48:53

标签: python tkinter tkinter-canvas

我正在尝试理解绑定和事件在python中是如何工作的。例如,我创建了3个瓷砖,并希望能够更改其中一个瓷砖的颜色,但无法理解或找出我出错的地方。我一直在说:

AttributeError: 'int' object has no attribute 'bind'.

以下是代码并提前致谢:

import tkinter

def main():

    root = tkinter.Tk()

    title = tkinter.Label(root, text="Test Window")
    title.pack()


    canvas= tkinter.Canvas(root, background='green', width = 300, height = 300)

    tile1=canvas.create_rectangle(0, 0, 100, 100, fill = 'magenta')
    tile2=canvas.create_rectangle(100,0, 200,100, fill = 'blue')
    tile3=canvas.create_rectangle(200,0, 300,100, fill = 'blue')

    canvas.pack()

    def change_square(event):
        event.configure(background = 'blue')

    tile1.bind("<Button-1>", change_square(tile1))

    root.mainloop()

if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:2)

itemconfigure会改变颜色:

def main():
    root = tkinter.Tk()

    title = tkinter.Label(root, text="Test Window")
    title.pack()

    canvas = tkinter.Canvas(root, background='green', width=300, height=300)

    s1 = canvas.create_rectangle(0, 0, 100, 100, fill='magenta')

    s2 = canvas.create_rectangle(100, 0, 200, 100, fill='blue')
    s3 = canvas.create_rectangle(200, 0, 300, 100, fill='blue')

    canvas.pack()

    def change_square(event):
        canvas.itemconfigure(s1, fill="blue")

    canvas.bind("<Button-1>", change_square)
    root.mainloop()

如果您想将中间值更改为黑色,请使用:

canvas.itemconfigure(s2, fill="black")`

等等。

如果你想根据你点击它来改变颜色,这应该起作用:

 def change_square(event):
        x = canvas.canvasx(event.x)
        y = canvas.canvasy(event.y)
        sq = canvas.find_closest(x,y)[0]
        canvas.itemconfigure(sq, fill="black")


    canvas.bind("<Button-1>", change_square)
    root.mainloop()