问题
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