这个问题与我如何在tkinter的Text小部件中看到输出“stdout
”有关。
输出由多处理产生。我开发了一个虚拟案例来更好地解释它:
import tkinter as tk
from tkinter import *
from tkinter import ttk
import sys
import time
import multiprocessing
from multiprocessing.dummy import Pool as ThreadPool
master = tk.Tk()
notebook = ttk.Notebook(master)
notebook.pack(fill='both', expand='yes')
frame1 = tk.Frame(notebook)
notebook.add(frame1, text='foo')
a = 0
def printing():
global a
a += 1
print(a)
def do_work(s):
time.sleep(s)
print(s)
def button():
List_of_works = [5,5,5,8,3,3,9,2]
pool = ThreadPool(multiprocessing.cpu_count())
pool.map(do_work, List_of_works)
pool.close()
pool.join()
frame1_1 = Frame(frame1)
Button_1 = Button(frame1_1, text='print_1', command=printing)
Button_1.grid(row=0, column=0, padx=1, pady=1)
Button_2 = Button(frame1_1, text='print_2', command=button)
Button_2.grid(row=1, column=0, padx=1, pady=1)
frame1_1.pack()
frame1_2 = Frame(frame1)
Textbox = Text(frame1_2, borderwidth=3, relief='ridge')
Textbox.grid(row=0, column=0, sticky="nsew", padx=2, pady=2)
frame1_2.pack(fill="both", expand=True)
class PrintToTextbox(object):
def write(self, s):
Textbox.insert(END, s)
#sys.stdout = PrintToTextbox()
#sys.stderr = PrintToTextbox()
master.geometry('200x300')
master.mainloop()
如您所见,执行代码时,我们可以看到两个按钮(print_1
和print_2
)。当我按下print_1
,(1,2,3,...)在IDLE中打印时,如果按print_2
,则会启动一个简单的多处理并打印值空闲。
然后我尝试将stdout重定向到Text
小部件。当您按#
时,删除尖锐符号(sys.stdout = PrintToTextbox()
)(print_1
),您可以在Text
窗口小部件中看到打印,但是如果按print_2
,程序没有打印任何东西,我不知道为什么。