Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reconfigure tkinter canvas items?

I don't know if this question has duplicates , but i haven't found one yet.

when using python you can create GUI fastly , but sometimes you cannot find a method to do what you want. for example i have the following problem:

let's suppose that there is a canvas called K with a rectangle with ID=1(canvas item id , not memory id) in it.

if i want to redraw the item i can delete it and then redraw it with new settings.

K.delete(1)
K.create_rectangle(x1,y1,x2,y2,options...)

here is the problem:the object id changes; how can i redraw or move or resize the rectangle or simply change it without changing its id with a method?for example:

K.foo(1,options....)

if there isn't such a method , then i should create a list with the canvas object ids , but it is not elegant and not fast.for example:

ItemIds=[None,None,etc...]
ItemIds[0]=K.create_rectangle(old options...)
K.delete(ItemIds[0])
ItemIds[0]=K.create_rectangle(new options...)
like image 663
Alberto Perrella Avatar asked Nov 03 '12 18:11

Alberto Perrella


1 Answers

You can use Canvas.itemconfig:

item = K.create_rectangle(x1,y1,x2,y2,options...)
K.itemconfig(item,options)

To move the item, you can use Canvas.move


import Tkinter as tk

root = tk.Tk()
canvas = tk.Canvas(root)
canvas.pack()
item = canvas.create_rectangle(50, 25, 150, 75, fill="blue")

def callback():
    canvas.itemconfig(item,fill='red')

button = tk.Button(root,text='Push me!',command=callback)
button.pack()

root.mainloop()
like image 135
mgilson Avatar answered Sep 28 '22 15:09

mgilson