在代码更改后重新加载Tkinter应用程序



我正在构建一个基于Tkinter的相对较大的应用程序。每当我进行代码更改时,我都必须手动重新加载应用程序,然后使用GUI返回到所需的状态。

例如,如果我在更改代码之前在应用程序中打开了一个图像,并且我想再次打开它,我必须首先打开GUI,从下拉列表中选择图像等等…这是浪费时间。是否有一种方法可以在代码更改后自动重新加载应用程序/GUI ?

这个问题已经被问过很多次了

从控制台重新加载python模块的正确方法

你可以使用reload(module),但是要小心副作用。例如,现有代码将基于原始代码,它不会神奇地获得添加的新属性或基类。

另一个很好的资源是https://code.activestate.com/recipes/580707-reload-tkinter-application-like-a-browser/

在你在评论中进一步描述了你的问题之后,我能够更好地在我这边重建这个问题。

这是我解决你的问题的基本实现:

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()

在本例中,我们能够更新GUI的背景颜色,并且它将在每次脚本重新运行时持续存在,直到它再次被手动更改。你可以把这个概念应用到你的应用程序中的任何一种状态,我想这应该能让你入门!

最新更新