Python3.8.1下创建独立日志打印窗口的实现咨询
Win10 64位 Python3.8 分窗口打印实现方案
方案1:标准库tkinter实现(无额外安装依赖)
tkinter是Python3.8自带的GUI库,无需额外pip安装,适合做轻量的独立文本输出窗口,和默认Python控制台完全隔离。
实现逻辑:封装单例的专属输出窗口类,复用同一个窗口实例,自定义printtowindow函数将指定内容追加到独立窗口的可滚动文本控件中,不干扰默认控制台的print输出。
完整测试代码:
import tkinter as tk from tkinter import scrolledtext import threading import time # 单例专属输出窗口 class CustomOutputWindow: _instance = None _root = None _text_box = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance def _init_window(self): self._root = tk.Tk() self._root.title("自定义输出窗口") self._root.geometry("600x400") # 带滚动条的文本框,支持自动换行 self._text_box = scrolledtext.ScrolledText(self._root, wrap=tk.WORD, font=("微软雅黑", 10)) self._text_box.pack(expand=True, fill="both") # 关闭窗口时默认隐藏,不退出主程序 self._root.protocol("WM_DELETE_WINDOW", lambda: self._root.withdraw()) # 启动tkinter事件循环 self._root.mainloop() def show_window(self): # 首次调用时初始化窗口,后台线程运行避免阻塞主程序 if not self._root: threading.Thread(target=self._init_window, daemon=True).start() # 等待窗口初始化完成,避免写入内容报错 while not self._text_box: time.sleep(0.1) else: # 已初始化的窗口直接重新显示 self._root.deiconify() def write(self, content): # 追加内容到窗口,自动滚动到最新位置 self._text_box.insert(tk.END, content + "\n") self._text_box.see(tk.END) # 封装为需求中的printtowindow函数 def printtowindow(content): win = CustomOutputWindow() win.show_window() win.write(str(content)) # --- 功能测试 --- if __name__ == "__main__": # 普通print走默认Python控制台 print('hello world') # 业务逻辑代码正常运行 calc_result = 1 + 2 print(f"普通控制台输出计算结果:{calc_result}") # 指定内容走独立专属窗口 printtowindow('this is not the python window') printtowindow(f"专属窗口输出计算结果:{calc_result}") # 主程序后续代码可正常运行,不受窗口干扰 time.sleep(10)
方案1注意事项
- 无额外依赖,Win10环境下的Python3.8直接可运行
- 窗口关闭时默认隐藏而非销毁,后续调用
printtowindow会自动重新弹出窗口 - 内容过多时自带滚动条,可上下拖动查看历史输出
方案2:新开独立CMD控制台窗口(黑窗口风格)
如果需要和默认Python控制台一致的命令行黑窗口效果,可通过subprocess新开一个独立的CMD进程,将自定义输出重定向到新窗口中。
完整测试代码:
import subprocess import time # 全局存储新开的CMD进程实例 _new_console = None def printtowindow(content): global _new_console # 首次调用时新开独立CMD窗口 if not _new_console: _new_console = subprocess.Popen( ["cmd.exe", "/k"], # /k参数表示执行完命令后保留窗口不自动关闭 stdin=subprocess.PIPE, text=True, bufsize=1 ) # 向新窗口写入输出内容 _new_console.stdin.write(f"echo {content}\n") _new_console.stdin.flush() # --- 功能测试 --- if __name__ == "__main__": # 普通print走默认Python控制台 print('hello world') # 业务逻辑代码正常运行 calc_result = 3 * 4 print(f"普通控制台输出计算结果:{calc_result}") # 指定内容走独立CMD窗口 printtowindow('this is not the python window') printtowindow(f"专属窗口输出计算结果:{calc_result}") # 主程序后续代码正常运行 time.sleep(10) # 主程序退出时自动关闭新开的CMD窗口,可根据需要添加 # _new_console.terminate()
方案2注意事项
- 新开的CMD窗口和默认控制台完全独立,输出互不干扰
- 如果主程序退出时需要自动关闭新开的CMD窗口,可在主程序退出逻辑中调用
_new_console.terminate() - 输出内容包含空格、引号等特殊字符时,需要对
echo的参数做转义,避免CMD解析错误
内容的提问来源于stack exchange,提问作者arioman
相关产品推荐
相关产品推荐

