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
235 views
in Technique[技术] by (71.8m points)

python - Tkinter access Canvas Objects created by Loop outside the loop

I am trying to manipulate some Canvas objects created by a loop on the Tkinter Canvas. Unfortunately I cannot access the the coordinates of these rectangles outside the loop, only one of them. How can I access all of the rectangles created by the loop outside the loop to get their coordinates, as well as manipulate them? This question might not make sense so please ask me if you don't understand and I will try to explain it better. Thanks!

    for y in range(2):
        for x in range(2):
            x1 = x*230
            y1 = y*230
            height = x1 + 200
            width = y1 + 200
            music_catalog_rect = canvas.create_rectangle((x1, y1, height, width), fill='red')
            canvas.move(music_catalog_rect, 180, 20)

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

1 Reply

0 votes
by (71.8m points)

You should store the items in some sort of data structure. You can then iterate over the structure to pick out specific values or iterate over all of the values.

For example, you might store them in a list:

rects = []
for y in range(2):
    for x in range(2):
        ...
        item = canvas.create_rectangle(...)
        rects.append(item)
        ...

This allows you to easily iterate over all of the items:

for item in rects:
    canvas.move(item, ...)

If keeping the x,y data is important, you can use the x,y as a key to a dictionary:

rects = {}
for y in range(2):
    for x in range(2):
        ...
        item = canvas.create_rectangle(...)
        rects[(x,y)] = item
        ...

Then later, you do something like the following:

canvas.move(rects[(3,4)], ...)

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

1.4m articles

1.4m replys

5 comments

56.8k users

...