Tkinter canvas create image multiple times












0














I use this function in my code to create an image on a canvas:



def _create_image(self, coord):
(x,y) = coord
self.one = ImageTk.PhotoImage(Image.open("test.jpg"))
root.one = self.one
self.canvas.create_image(x-25, y-25, image=self.one, anchor='nw', tags="image")


My problem is that everytime i call this function the old image is deleted and a new one is created.



How do i prevent the old image from being deleted? I want to create the image multiple times on my canvas.










share|improve this question
























  • Possible duplicate of Using an tkinter image canvas in a loop
    – stovfl
    Nov 16 '18 at 21:27
















0














I use this function in my code to create an image on a canvas:



def _create_image(self, coord):
(x,y) = coord
self.one = ImageTk.PhotoImage(Image.open("test.jpg"))
root.one = self.one
self.canvas.create_image(x-25, y-25, image=self.one, anchor='nw', tags="image")


My problem is that everytime i call this function the old image is deleted and a new one is created.



How do i prevent the old image from being deleted? I want to create the image multiple times on my canvas.










share|improve this question
























  • Possible duplicate of Using an tkinter image canvas in a loop
    – stovfl
    Nov 16 '18 at 21:27














0












0








0







I use this function in my code to create an image on a canvas:



def _create_image(self, coord):
(x,y) = coord
self.one = ImageTk.PhotoImage(Image.open("test.jpg"))
root.one = self.one
self.canvas.create_image(x-25, y-25, image=self.one, anchor='nw', tags="image")


My problem is that everytime i call this function the old image is deleted and a new one is created.



How do i prevent the old image from being deleted? I want to create the image multiple times on my canvas.










share|improve this question















I use this function in my code to create an image on a canvas:



def _create_image(self, coord):
(x,y) = coord
self.one = ImageTk.PhotoImage(Image.open("test.jpg"))
root.one = self.one
self.canvas.create_image(x-25, y-25, image=self.one, anchor='nw', tags="image")


My problem is that everytime i call this function the old image is deleted and a new one is created.



How do i prevent the old image from being deleted? I want to create the image multiple times on my canvas.







python canvas tkinter tkinter-canvas






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '18 at 20:48









petezurich

3,50581734




3,50581734










asked Nov 16 '18 at 20:45









K-Doe

8911




8911












  • Possible duplicate of Using an tkinter image canvas in a loop
    – stovfl
    Nov 16 '18 at 21:27


















  • Possible duplicate of Using an tkinter image canvas in a loop
    – stovfl
    Nov 16 '18 at 21:27
















Possible duplicate of Using an tkinter image canvas in a loop
– stovfl
Nov 16 '18 at 21:27




Possible duplicate of Using an tkinter image canvas in a loop
– stovfl
Nov 16 '18 at 21:27












3 Answers
3






active

oldest

votes


















1














First create a list in for example __init__().



self.img_ref = 


Then append each new image to this list as you create them:



def _create_image(self, coord):
(x,y) = coord
self.one = ImageTk.PhotoImage(Image.open("test.jpg"))
root.one = self.one
self.canvas.create_image(x-25, y-25, image=self.one,
anchor='nw', tags="image")
self.img_ref.append(self.one) # Keep reference to image


Even if every image is the same image you have to keep a reference to each one.






share|improve this answer





















  • Perfect! Thank you very much.
    – K-Doe
    Nov 16 '18 at 21:30



















1














You don't need to modify the __init__() method nor store a list of references since it's always the same image file. Here something that avoids using unnecessary resource, so would therefore use less memory (and likely be faster, too).



It accomplishes this by testing to see whether the one attribute already exists or not, and if not, only then reads the image data and creates the PImageTk.PhotoImagehotoImage that first time.



This approach allows you to create multiple Canvas widget image objects from the same ImageTk.PhotoImage, instead of loading multiple copies of it into memory.



def _create_image(self, coord):
(x,y) = coord

if not getattr(self, 'one', None): # First call?
pil_img = Image.open("test.jpg")
self.one = ImageTk.PhotoImage(pil_img)

self.canvas.create_image(x-25, y-25, image=self.one,
anchor='nw', tags="image")


You could also do the creation of the ImageTk.PhotoImage all in one line:



    # pil_img = Image.open("test.jpg")  # Leave out.
self.one = ImageTk.PhotoImage(file="test.jpg")





share|improve this answer































    0














    Image.open() will rewrite the image each time.






    share|improve this answer























    • Calling Image.open() multiple times wouldn't rewrite anything, it will return a new PIL image object each time.
      – martineau
      Nov 16 '18 at 22:19










    • @martineau ah yes i apologize i must have confused this with something else
      – Amar Nabhani
      Nov 16 '18 at 22:21






    • 1




      This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
      – Sebastian 506563
      Nov 16 '18 at 22:59











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53345143%2ftkinter-canvas-create-image-multiple-times%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    First create a list in for example __init__().



    self.img_ref = 


    Then append each new image to this list as you create them:



    def _create_image(self, coord):
    (x,y) = coord
    self.one = ImageTk.PhotoImage(Image.open("test.jpg"))
    root.one = self.one
    self.canvas.create_image(x-25, y-25, image=self.one,
    anchor='nw', tags="image")
    self.img_ref.append(self.one) # Keep reference to image


    Even if every image is the same image you have to keep a reference to each one.






    share|improve this answer





















    • Perfect! Thank you very much.
      – K-Doe
      Nov 16 '18 at 21:30
















    1














    First create a list in for example __init__().



    self.img_ref = 


    Then append each new image to this list as you create them:



    def _create_image(self, coord):
    (x,y) = coord
    self.one = ImageTk.PhotoImage(Image.open("test.jpg"))
    root.one = self.one
    self.canvas.create_image(x-25, y-25, image=self.one,
    anchor='nw', tags="image")
    self.img_ref.append(self.one) # Keep reference to image


    Even if every image is the same image you have to keep a reference to each one.






    share|improve this answer





















    • Perfect! Thank you very much.
      – K-Doe
      Nov 16 '18 at 21:30














    1












    1








    1






    First create a list in for example __init__().



    self.img_ref = 


    Then append each new image to this list as you create them:



    def _create_image(self, coord):
    (x,y) = coord
    self.one = ImageTk.PhotoImage(Image.open("test.jpg"))
    root.one = self.one
    self.canvas.create_image(x-25, y-25, image=self.one,
    anchor='nw', tags="image")
    self.img_ref.append(self.one) # Keep reference to image


    Even if every image is the same image you have to keep a reference to each one.






    share|improve this answer












    First create a list in for example __init__().



    self.img_ref = 


    Then append each new image to this list as you create them:



    def _create_image(self, coord):
    (x,y) = coord
    self.one = ImageTk.PhotoImage(Image.open("test.jpg"))
    root.one = self.one
    self.canvas.create_image(x-25, y-25, image=self.one,
    anchor='nw', tags="image")
    self.img_ref.append(self.one) # Keep reference to image


    Even if every image is the same image you have to keep a reference to each one.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 16 '18 at 21:22









    figbeam

    2,765137




    2,765137












    • Perfect! Thank you very much.
      – K-Doe
      Nov 16 '18 at 21:30


















    • Perfect! Thank you very much.
      – K-Doe
      Nov 16 '18 at 21:30
















    Perfect! Thank you very much.
    – K-Doe
    Nov 16 '18 at 21:30




    Perfect! Thank you very much.
    – K-Doe
    Nov 16 '18 at 21:30













    1














    You don't need to modify the __init__() method nor store a list of references since it's always the same image file. Here something that avoids using unnecessary resource, so would therefore use less memory (and likely be faster, too).



    It accomplishes this by testing to see whether the one attribute already exists or not, and if not, only then reads the image data and creates the PImageTk.PhotoImagehotoImage that first time.



    This approach allows you to create multiple Canvas widget image objects from the same ImageTk.PhotoImage, instead of loading multiple copies of it into memory.



    def _create_image(self, coord):
    (x,y) = coord

    if not getattr(self, 'one', None): # First call?
    pil_img = Image.open("test.jpg")
    self.one = ImageTk.PhotoImage(pil_img)

    self.canvas.create_image(x-25, y-25, image=self.one,
    anchor='nw', tags="image")


    You could also do the creation of the ImageTk.PhotoImage all in one line:



        # pil_img = Image.open("test.jpg")  # Leave out.
    self.one = ImageTk.PhotoImage(file="test.jpg")





    share|improve this answer




























      1














      You don't need to modify the __init__() method nor store a list of references since it's always the same image file. Here something that avoids using unnecessary resource, so would therefore use less memory (and likely be faster, too).



      It accomplishes this by testing to see whether the one attribute already exists or not, and if not, only then reads the image data and creates the PImageTk.PhotoImagehotoImage that first time.



      This approach allows you to create multiple Canvas widget image objects from the same ImageTk.PhotoImage, instead of loading multiple copies of it into memory.



      def _create_image(self, coord):
      (x,y) = coord

      if not getattr(self, 'one', None): # First call?
      pil_img = Image.open("test.jpg")
      self.one = ImageTk.PhotoImage(pil_img)

      self.canvas.create_image(x-25, y-25, image=self.one,
      anchor='nw', tags="image")


      You could also do the creation of the ImageTk.PhotoImage all in one line:



          # pil_img = Image.open("test.jpg")  # Leave out.
      self.one = ImageTk.PhotoImage(file="test.jpg")





      share|improve this answer


























        1












        1








        1






        You don't need to modify the __init__() method nor store a list of references since it's always the same image file. Here something that avoids using unnecessary resource, so would therefore use less memory (and likely be faster, too).



        It accomplishes this by testing to see whether the one attribute already exists or not, and if not, only then reads the image data and creates the PImageTk.PhotoImagehotoImage that first time.



        This approach allows you to create multiple Canvas widget image objects from the same ImageTk.PhotoImage, instead of loading multiple copies of it into memory.



        def _create_image(self, coord):
        (x,y) = coord

        if not getattr(self, 'one', None): # First call?
        pil_img = Image.open("test.jpg")
        self.one = ImageTk.PhotoImage(pil_img)

        self.canvas.create_image(x-25, y-25, image=self.one,
        anchor='nw', tags="image")


        You could also do the creation of the ImageTk.PhotoImage all in one line:



            # pil_img = Image.open("test.jpg")  # Leave out.
        self.one = ImageTk.PhotoImage(file="test.jpg")





        share|improve this answer














        You don't need to modify the __init__() method nor store a list of references since it's always the same image file. Here something that avoids using unnecessary resource, so would therefore use less memory (and likely be faster, too).



        It accomplishes this by testing to see whether the one attribute already exists or not, and if not, only then reads the image data and creates the PImageTk.PhotoImagehotoImage that first time.



        This approach allows you to create multiple Canvas widget image objects from the same ImageTk.PhotoImage, instead of loading multiple copies of it into memory.



        def _create_image(self, coord):
        (x,y) = coord

        if not getattr(self, 'one', None): # First call?
        pil_img = Image.open("test.jpg")
        self.one = ImageTk.PhotoImage(pil_img)

        self.canvas.create_image(x-25, y-25, image=self.one,
        anchor='nw', tags="image")


        You could also do the creation of the ImageTk.PhotoImage all in one line:



            # pil_img = Image.open("test.jpg")  # Leave out.
        self.one = ImageTk.PhotoImage(file="test.jpg")






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 16 '18 at 23:03

























        answered Nov 16 '18 at 22:14









        martineau

        65.9k989177




        65.9k989177























            0














            Image.open() will rewrite the image each time.






            share|improve this answer























            • Calling Image.open() multiple times wouldn't rewrite anything, it will return a new PIL image object each time.
              – martineau
              Nov 16 '18 at 22:19










            • @martineau ah yes i apologize i must have confused this with something else
              – Amar Nabhani
              Nov 16 '18 at 22:21






            • 1




              This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
              – Sebastian 506563
              Nov 16 '18 at 22:59
















            0














            Image.open() will rewrite the image each time.






            share|improve this answer























            • Calling Image.open() multiple times wouldn't rewrite anything, it will return a new PIL image object each time.
              – martineau
              Nov 16 '18 at 22:19










            • @martineau ah yes i apologize i must have confused this with something else
              – Amar Nabhani
              Nov 16 '18 at 22:21






            • 1




              This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
              – Sebastian 506563
              Nov 16 '18 at 22:59














            0












            0








            0






            Image.open() will rewrite the image each time.






            share|improve this answer














            Image.open() will rewrite the image each time.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 17 '18 at 7:48









            Benyamin Jafari

            2,77732036




            2,77732036










            answered Nov 16 '18 at 21:14









            Amar Nabhani

            1




            1












            • Calling Image.open() multiple times wouldn't rewrite anything, it will return a new PIL image object each time.
              – martineau
              Nov 16 '18 at 22:19










            • @martineau ah yes i apologize i must have confused this with something else
              – Amar Nabhani
              Nov 16 '18 at 22:21






            • 1




              This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
              – Sebastian 506563
              Nov 16 '18 at 22:59


















            • Calling Image.open() multiple times wouldn't rewrite anything, it will return a new PIL image object each time.
              – martineau
              Nov 16 '18 at 22:19










            • @martineau ah yes i apologize i must have confused this with something else
              – Amar Nabhani
              Nov 16 '18 at 22:21






            • 1




              This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
              – Sebastian 506563
              Nov 16 '18 at 22:59
















            Calling Image.open() multiple times wouldn't rewrite anything, it will return a new PIL image object each time.
            – martineau
            Nov 16 '18 at 22:19




            Calling Image.open() multiple times wouldn't rewrite anything, it will return a new PIL image object each time.
            – martineau
            Nov 16 '18 at 22:19












            @martineau ah yes i apologize i must have confused this with something else
            – Amar Nabhani
            Nov 16 '18 at 22:21




            @martineau ah yes i apologize i must have confused this with something else
            – Amar Nabhani
            Nov 16 '18 at 22:21




            1




            1




            This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
            – Sebastian 506563
            Nov 16 '18 at 22:59




            This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
            – Sebastian 506563
            Nov 16 '18 at 22:59


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53345143%2ftkinter-canvas-create-image-multiple-times%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            How to send String Array data to Server using php in android

            Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

            Is anime1.com a legal site for watching anime?