如何解决Python:如何登录另一个脚本运行的脚本?
我使用记录器制作了一个GUI,该GUI很好用,但现在我也使该程序有可能启动用户加载的另一个脚本。
所以我要做的是在主文件(main.py)中启动gui:
def main_loop():
while True:
do_something()
def main():
root = gui.tk.Tk()
t1 = threading.Thread(target=main_loop,args=[])
t1.start()
root.mainloop()
t1.join()
if __name__ == "__main__":
main()
这将使用记录器(gui.py)打开我的GUI。 记录器如下所示:
# LOGGER
class TextHandler(logging.Handler):
def __init__(self,text):
logging.Handler.__init__(self)
self.text = text
def emit(self,record):
msg = self.format(record)
def append():
self.text.configure(state='normal')
self.text.insert(tk.END,msg + '\n')
self.text.configure(state='disabled')
self.text.yview(tk.END)
self.text.after(0,append)
class my_gui(tk.Frame):
def __init__(self,parent,*args,**kwargs):
tk.Frame.__init__(self,**kwargs)
self.root = parent
self.build_gui()
def build_gui(self):
# Build GUI
st = ScrolledText.ScrolledText(tab3,state='disabled')
st.configure(font='TkFixedFont')
st.grid(column=0,row=1,sticky='w',columnspan=4)
# Create textLogger
text_handler = TextHandler(st)
# Logging configuration
logging.basicConfig(filename='logger.log',level=logging.INFO,format='%(asctime)s - %(levelname)s - %(message)s')
# Add the handler to logger
logger = logging.getLogger()
logger.addHandler(text_handler)
现在登录通常可以正常工作,但是在GUI中,我还具有此功能以允许用户运行自己的脚本(这也是my_gui类的一部分):
def load_script():
my_gui.filename = filedialog.askopenfilename(initialdir="/",title="Select file",filetypes=(("python_script","*.py"),("all files","*.*")))
script_text = tk.Label(tab3,text=f"Current script: {my_gui.filename}")
script_text.grid(column=1,row=0,pady=(3,3),padx=(3,sticky='w')
def start_script(path):
subprocess.run([sys.executable,path],check=True)
start_script_button = ttk.Button(tab3,text="Start Script",command=lambda: start_script(my_gui.filename))
start_script_button.grid(column=2,sticky='w')
get_script_button = ttk.Button(tab3,text="Load Your Script",command=load_script)
get_script_button.grid(column=0,sticky='w')
问题是我无法使用用户脚本登录到记录器。打印到日志文件是可行的,但是它仍然无法在GUI上对其进行更新。如果有人有什么想法,将不胜感激。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。