Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reload Tkinter application after code change

Tags:

python

tkinter

I am building a relatively large application based on Tkinter. Whenever I make a code change, I have to reload the application manually, and then use the GUI to go back to the desired state.

For instance, if I had open an image in the app before changing the code, and I want to open it again, I have first to open the GUI, select the image from the drop-down list and so on... This is a waste of time. Is there a way to automatically reload the application/GUI after a code change in the last state it was?

like image 437
Tommaso Bendinelli Avatar asked Feb 02 '26 19:02

Tommaso Bendinelli


1 Answers

This question has been asked a number of times

Proper way to reload a python module from the console

You can use reload(module) for this, but beware of nasty side effects. For example, existing code will be based on the original code, it will not magically get new attributes or baseclasses added.

Another great resource on this would be https://code.activestate.com/recipes/580707-reload-tkinter-application-like-a-browser/

After you've described you're problem a bit further in the comments, I was able to reconstruct the issue better on my end.

Here's my basic implementation for a solution to your issue:

from tkinter import *
import json

application_state = {"background": "white"}  
background_colors = ["white", "red", "blue", "yellow", "green"]


def main():
   root = Tk()
   root.title("Test")
   root.geometry("400x400")
   reload_state(root)

   for color in background_colors:
      def change_background_wrapper(color=color, root=root):
         change_background(color, root)

      Button(root, text=color,command=change_background_wrapper).pack()

   root.mainloop()


def change_background(color, window):
   print("new color: " + color)
   window.configure(bg=color)
   application_state["background"] = color
   update_config()


def reload_state(window):
   config_file = open("config.json")
   conf = json.load(config_file)
   window.configure(bg=conf["background"])


def update_config():
   with open("config.json", "w") as conf:
      conf.write(json.dumps(application_state))


if __name__ == "__main__":
   main()

In this instance, we're able to update the background color of the GUI and it will persist on each rerun of the script, until it gets manually changed again. You can apply this concept to pretty much any sort of state you have inside your application, I think this should get you started!

like image 52
Bialomazur Avatar answered Feb 05 '26 08:02

Bialomazur