16

I want to change the canvas size after I have added some widgets to it

Example:

from Tkinter import * 

master = Tk()
w = Canvas(master, width=100, height=100)
w.config(bg='white')
w.create_oval(90,90,110,110, width=0, fill = "ivory3")
w = Canvas(master, width=200, height=200)
w.pack()
mainloop()

But it seem that when I re-declare the canvas size, the objects get removed. Is it possible to update the canvas after I have created some objects on it?

2 Answers 2

36

What you are looking for is the configure option, as is documentered here. Basically, something like this should help, in place of creating a new canvas:

w.config(width=200, height=200)

For reference, the reason why everything got deleted off of the Canvas is because you created a brand new Canvas, with a different size and the same name. If you are going to change properties of an existing object, you must change the existing object, and not overwrite it. Basically you overwrite something if you declare it equal to something else (w=Canvas(...)).

Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant. Thank you, I was trying allsort - update, modify etc, I didn't think of config. Appreciated. Of course it works like a charm.
2

You can easily resize to canvas with the .config() command like so:

w.config(width=x height=y)

The x and y represent integers (whole numbers). You can also add on some other customisation attributes like bg (background) to further customise the canvas.

Also, you have created a brand new canvas at the end there so that is why your attributes disappeared. You can fix that by deleting the last 2 lines of code starting with w =.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.