简体   繁体   中英

How would I make my movebal square change colors by clicking another square on my canvas?

So I have a red square that you can move around with the arrow keys, and I have these other 3 squares in the upper left hand corner of the canvas. They are red, green, and blue. If you click inside one of the squares I would like it to turn the movable square to that color of the square that was clicked. I'm not sure how to go about doing this any help would be greatly appreciated here is my code so far.

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)

Edit* I'm on the right track now I just figured out the onMouseDown(event) still a little confused on how to make it work though with clicking each square to change color.

Well figured it out myself. I had to use the canvas.tag_bind. to bind the mouse button to one of my shapes to change the color. Here is what I did for anyone who may need this example.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM