问题陈述
我创建了一个 python 3.6
执行一些数据转换并使用 tkinter
的脚本用于 GUI(文件夹选择和其他选项)。
我已将其转换为 exe
文件使用 pyinstaller
& 希望其他用户(没有安装 python)能够使用该工具。
但是,当我打开exe
,它打开一个 CMD window
它显示了通常显示在 python console
上的日志.
我想将此重定向到 text box
或 frame
在我的 tkinter
窗口本身 - 而不是在单击时打开一个新的 CMD 窗口。
示例代码
import tkinter as tk
from tkinter import filedialog as fd
def browse():
directory=fd.askdirectory()
print ('The selected directory is: ', directory)
def convert():
# perform file manipulation
print ("Files converted")
window = tk.Tk()
window.title("Title")
label=tk.Label(window,text="Instructions")
label.pack()
browseButton=tk.Button(window,text="Browse Folder", command=browse)
browseButton.pack(pady=10)
runButton=tk.Button(window,text="Convert files", command=convert)
runButton.pack(pady=10)
window.mainloop()
然后我将文件转换为
exe
使用 pyinstaller
> pyinstaller --onefile TkinterGUI_test.py
预期结果
我在 stackoverflow 上看到了许多相关但不符合我的要求的帖子。任何帮助将不胜感激。谢谢! :)
最佳答案
要隐藏控制台,您需要添加 --noconsole
到您的 pyinstaller 命令。
为了重定向您的打印输出,您可以使用以下内容:
import tkinter as tk
import sys
class PrintLogger(): # create file like object
def __init__(self, textbox): # pass reference to text widget
self.textbox = textbox # keep ref
def write(self, text):
self.textbox.insert(tk.END, text) # write text to textbox
# could also scroll to end of textbox here to make sure always visible
def flush(self): # needed for file like object
pass
if __name__ == '__main__':
def do_something():
print('i did something')
root.after(1000, do_something)
root = tk.Tk()
t = tk.Text()
t.pack()
# create instance of file like object
pl = PrintLogger(t)
# replace sys.stdout with our object
sys.stdout = pl
root.after(1000, do_something)
root.mainloop()
因为打印语句通过替换我们在文本框中得到的输出来将其输出定向到 sys.stdout,这意味着
print
插入换行符和它通常会在终端中执行的任何其他操作。
关于python-3.x - 如何在执行使用 pyinstaller 创建的 exe 文件时在我的 tkinter 窗口而不是 CMD 窗口上获取 python 控制台日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53721337/