熟悉VS代码的活动服务器的人很容易理解这个问题的主要动机是什么。
但对其他人来说,这是一个解释:
我尝试过在web上以及在堆栈上搜索流,但是所有的结果都是为了更新条目、标签、按钮等的值。但我想要的是,当我更改主文件中的某个内容时,整个窗口都应该被更新,主窗口不应该被重新打开。因此,简而言之,更新整个窗口而不关闭它,对主文件中的每一项更改,或者在保存时自动重新加载程序而不重新打开!
我试过什么?:
os.getsize检测文件中的变化,这满足了我问题的第一部分,但是我无法解决第二部分,即窗口不应该关闭。import os
main__tkinter_filename="myfile.py"
initial_filesize=os.path.getsize(main_tkinter_filename) # Getting size of the file for
# comparison.
while 1:
final_filesize=os.path.getsize(main_tkinter_filename)
if final_filsize<intial_filesize or final_filesize>initial_filesize:
webbrowser.open(main_tkinter_filename)示例:
from tkinter import *
root=Tk()
root.mainloop结果在下面的GUI中:

如果我在a=Label(text='text')之后添加了root=Tk()和a.pack(),它应该向我显示标签,如果我删除了相同的代码,它应该删除它们。
发布于 2022-04-07 12:46:20
在深入研究之后,我终于找到了一种实现热重加载功能的方法( @Stange答案提供的),但只是更新了所选的框架或代码。
基本思想是持续读取文件并执行所选代码,并删除要删除的列表中的对象。
# Live Checker.py
import keyboard
while 1:
if keyboard.is_pressed("Ctrl+r"):
with open('test.py','r') as file:
file_data=file.read()
file_data_start_index=file_data.find("'@Start@'")
file_data_end_index=file_data.find("'@End@'")
exec_command=file_data[file_data_start_index:file_data_end_index]
with open('exec_log.txt','w') as txt_file:
txt_file.write(exec_command)在这里,我经常检查是否按下了ctrl+r键,是否按下了
@Start@和@End@更新的代码的开始和结束。# Main.py
def check():
with open('exec_log.txt','r') as exec_c:
exec_command=exec_c.read()
if len(exec_command)==0:
pass
else:
print(exec_command)
exec('for i in root.winfo_children():i.destroy()\n'+exec_command)
print('exec')
with open('exec_log.txt','w') as exec_c:
pass
root.update()
root.after(100,check)
root.after(100,check)在主文件中,我添加了上面的代码,连续检查exec_log.txt文件是否有任何更改,如果有更改,则执行这些更改,从而破坏remove_list中指定的小部件。
这只是一个临时的解决方案,在我的例子中,它帮助我在tkinter中实现热重加载功能。
https://stackoverflow.com/questions/71546744
复制相似问题