Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

python - 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...)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...