Python Forum
Putting code into a function breaks its functionality, though the code is identical!
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Putting code into a function breaks its functionality, though the code is identical!
#2
The difference is the context. Literally.

When you run the code in a function and create variables like this:
newimage = ImageTk.PhotoImage(Image.open(imgstring))
the new image is only referenced by a variable (newimage) in the FUNCTION namespace. When the function is done and cleans up after itself the function variables are tossed in the trash and garbage collected. Since there are now no references to the image, the image is also tossed in the trash for garbage collection.

When you run the same code outside a function the new image is reverenced by a variable in the GLOBAL namespace. Global variables hang around as long as the module containing them, essentially forever as far as you program is concerned. If you were to del the variable the reference count for the image would go to zero and your image would get tossed in the trash and garbage collected.

If you want to use an image in tkinter you need a variable to reference the image and the variable must be a GLOBAL variable, a CLASS variable, or an INSTANCE variable. FUNCTION variables are not good for this.
Reply


Messages In This Thread
RE: Putting code into a function breaks its functionality, though the code is identical! - by deanhystad - Apr-05-2021, 05:40 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Copying the order of another list with identical values gohanhango 7 1,309 Nov-29-2023, 09:17 PM
Last Post: Pedroski55
  Variable is not defined error when trying to use my custom function code fnafgamer239 4 687 Nov-23-2023, 02:53 PM
Last Post: rob101
  My code works on Jupyter Lab/Notebook, but NOT on Visual Code Editor jst 4 1,309 Nov-15-2023, 06:56 PM
Last Post: jst
  the order of running code in a decorator function akbarza 2 614 Nov-10-2023, 08:09 AM
Last Post: akbarza
Sad I'm stuck with the reinforcement learning function in my Code OskiLori 2 1,683 May-20-2023, 10:01 PM
Last Post: OskiLori
  Tie Breaks klatlap 6 1,205 Mar-20-2023, 12:08 PM
Last Post: klatlap
  Priority Queue with update functionality PythonNewbee 4 2,136 Dec-29-2022, 12:13 PM
Last Post: Yoriz
  python multiple try except block in my code -- can we shorten code mg24 10 6,575 Nov-10-2022, 12:48 PM
Last Post: DeaD_EyE
  faster code for my code kucingkembar 19 3,514 Aug-09-2022, 09:48 AM
Last Post: DPaul
  Changing a string value to a numerical value using python code and a lamda function Led_Zeppelin 6 1,743 Jul-05-2022, 11:29 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020