How to get python console logs on my tkinter window instead of a CMD window while executing an exe file created using pyinstaller

a 夏天 提交于 2020-12-13 03:18:17

问题


Problem statement

I have created a python 3.6 script that performs some data conversion and uses tkinter for GUI (folder selection and other options).

I have converted this to an exe file using pyinstaller & would like other users (who don't have python installed) to be able to use the tool.

However, when I open the exe, it opens a CMD window which shows the logs usually shown on the python console.

I'd like to get this redirected to a text box or frame in my tkinter window itself - instead of opening a new CMD window when clicked.

Sample code

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

Then I convert the file to exe using pyinstaller

> pyinstaller --onefile TkinterGUI_test.py

Expected result

I have seen numerous posts on stackoverflow which are related but don't match my requirements. Any help would be highly appreciated. Thanks! :)


回答1:


to hide the console you need to add the --noconsole to your pyinstaller command.

in order to redirect your printed output you could use something like this:

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

because the print statement directs its output at sys.stdout by replacing the output we get exactly the same in the textbox, this means that print inserts newlines and anything else it would normally do in the terminal.



来源:https://stackoverflow.com/questions/53721337/how-to-get-python-console-logs-on-my-tkinter-window-instead-of-a-cmd-window-whil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!