Use Tkinter to create GUI development tools (43) Tkinter takes over print output statements

Use Tkinter to build GUI development tools (43) Tkinter takes over the print output statement.
In the previous blog, we introduced using Tkinter as a Python editor. We saw that we can run Python code. The question is, where is the code output? If it is not in the Python editor, we cannot see the output.
So we need to get the print statement output information in the program.
Xiaobai Quantitative Framework has provided ready-made functions in HP_tk module, users only need to use it.
The demo code is directly given below, with detailed comments.

#小白量化用户Python代码编辑器,输出演示
#独狼荷蒲qq:2886002
#通通小白python量化群:524949939
#微信公众号:独狼股票分析
import  HP_tk  as  htk   #导入htk

#创建输入输出控制权对象myconsole
myconsole=htk.console2()

#获取系统输入input/输出print权
#接管print()函数
myconsole.SwitchOut2(sw=True)
#第一次print
print('1.我想输出信息!')

#获取print语句输出信息
s=myconsole.text
#如果需要清空text缓存可以用clear()方法
#myconsole.clear()

#释放print权利给Python系统,同时返回text输出信息
s2=myconsole.SwitchOut2(sw=False)

#清除print语句输出信息缓存
myconsole.clear()


#第二次print
print('2.刚才输出的什么信息? s=',s)
print('3.刚才输出的什么信息? s2=',s2)

The program input results in Spyder are as follows:

runfile('D:/xb2/小白输出演示2.py', wdir='D:/xb2')
Reloaded modules: HP_tk
2.刚才输出的什么信息? s= 1.我想输出信息!

3.刚才输出的什么信息? s2= 1.我想输出信息!

We can clearly see in the above program that the first print output "print('1. I want to output information!')" was taken over by the program.
When the program releases the print takeover right, the print statement is allowed to output information.

Let's give an example of outputting the multiplication formula table to Tkinter's Text control using the print statement.

#小白量化用户Python代码编辑器,输出演示
#独狼荷蒲qq:2886002
#通通小白python量化群:524949939
#微信公众号:独狼股票分析
import  tkinter  as  tk   #导入Tkinter
import  HP_tk  as  htk   #导入htk

#创建Tkinterz主窗口
root=tk.Tk()
root.title('Tkinter的print输出演示')
root.geometry('{}x{}+{}+{}'.format(800,600,100,100))

#创建Text文本编辑控件
txt=tk.Text()
txt.pack(fill=tk.BOTH, expand=tk.YES) #铺满Tkinter主窗口


#创建输入输出控制权对象myconsole
myconsole=htk.console2()

#获取系统输入input/输出print权
#接管print()函数
myconsole.SwitchOut2(sw=True)

#输出乘法口诀表
print('\n'.join([' '.join(['%s*%s=%-2s'%(y,x,x*y) for y in range(1,x+1)]) for x in range(1,10)]))
#上面的print语句没有在控制台上输出.

#释放print权利给Python系统,同时返回text输出信息
s2=myconsole.SwitchOut2(sw=False)

#清除print语句输出信息缓存
myconsole.clear()

#将截获的print输出信息,输入到Text控件中.
txt.insert(tk.END, s2)

root.mainloop()

The program running results are as follows, there is no output information on the Spyder console.

runfile('D:/xb2/小白输出演示3.py', wdir='D:/xb2')
Reloaded modules: HP_tk

The running graphics are as follows:

Insert picture description here
Through the above introduction, our readers can use Tkiter to design a simple Python code editor.

Guess you like

Origin blog.csdn.net/hepu8/article/details/107003844