如何通过点击画布上的另一个方块来使我的移动方块改变颜色?

时间:2014-11-10 04:54:20

标签: python animation canvas tkinter

所以我有一个红色方块,你可以用箭头键移动,我在画布的左上角有其他3个方块。它们是红色,绿色和蓝色。如果你在其中一个正方形内部点击,我希望它将可移动的正方形转换为所点击的正方形的颜色。我不知道如何去做这个任何帮助将非常感谢这里是我的代码到目前为止。

from tkinter import*



def onKeyDown(event):
    if(event.keysym == "Up"):
        canvas.move(rect, 0, -2)
    if(event.keysym == "Down"):
        canvas.move(rect, 0, 2)
    if(event.keysym == "Left"):
        canvas.move(rect, -2, 0)
    if(event.keysym == "Right"):
        canvas.move(rect, 2, 0)

def onMouseDown(event):
    canvas.itemconfigure(rect, fill="green");






master = Tk()
canvas = Canvas(master, width=600, height=600)
canvas.pack()
rect = canvas.create_rectangle(250,250,350,350, fill="red")
canvas.update()

rrect = canvas.create_rectangle(0,0,30,30, fill="red")
grect = canvas.create_rectangle(33,0,60,30, fill="green")
brect = canvas.create_rectangle(63,0,90,30, fill="blue")
master.bind("<Key>", onKeyDown)  
master.bind("<Button-1>", onMouseDown)

编辑*我现在正走在正确的轨道上我只是弄清楚onMouseDown(事件)仍然有点困惑如何让它工作,虽然点击每个方块来改变颜色。

1 个答案:

答案 0 :(得分:2)

我自己想通了。我不得不使用canvas.tag_bind。将鼠标按钮绑定到我的一个形状以更改颜色。这是我为可能需要这个例子的人所做的。

from tkinter import*



def onKeyDown(event):
    if(event.keysym == "Up"):
        canvas.move(rect, 0, -2)
    if(event.keysym == "Down"):
        canvas.move(rect, 0, 2)
    if(event.keysym == "Left"):
        canvas.move(rect, -2, 0)
    if(event.keysym == "Right"):
        canvas.move(rect, 2, 0)


def onClick1(event):
    canvas.itemconfigure(rect, fill="red");
def onClick2(event):
    canvas.itemconfigure(rect, fill="green");
def onClick3(event):
    canvas.itemconfigure(rect, fill="blue")




master = Tk()
canvas = Canvas(master, width=600, height=600)
canvas.pack()
rect = canvas.create_rectangle(250,250,350,350, fill="red")
canvas.update()

rrect = canvas.create_rectangle(0,0,30,30, fill="red")
grect = canvas.create_rectangle(33,0,60,30, fill="green")
brect = canvas.create_rectangle(63,0,90,30, fill="blue")

master.bind("<Key>", onKeyDown)

canvas.tag_bind(rrect,"<Button-1>", onClick1)
canvas.tag_bind(grect,"<Button-1>", onClick2)
canvas.tag_bind(brect,"<Button-1>", onClick3)