不能用Text.insert,因为定义的函数print语句有很多,在控制台是可以用print进行输出,但是Text.insert不支持带有print的函数,
Text.insert中用的函数只能是函数的返回值return,但是如果用返回值就只能返回一个print的语句,text框中出现的只有一句话,其他的都会失效。
另外尝试用yield,让函数可以有多个return的语句返回,但是最后还是要用到print遍历出来或者转化为元组模式,跟原来的函数输出格式天差地别。
这问题困扰了一整天,该怎么破?希望大神搭救。
(如果可以请说清楚点,谢谢)
好像没人回答,我自己想了一个办法,就是创建一个txt文本,
然后把print的内容写入txt里面,关闭,然后再打开,读取里面的全部内容,传递给all_the_text,
最后在Text.insert里面使用all_the_text,这样就能实现原格式输出了,不过总感觉哪里怪怪的。
import tkinter as tk
import time
root=tk.Tk()
root.title("how to do ")
root.geometry('500x600')
tk.Label(root, text="显示", bg="green", font=("Arial", 12), width=5, height=1).place(x=20,y=30)
def A():
for i in range(100):
time.sleep(1) #间隔1秒输出
if i < 3:
yield ("编号{},字符串A".format(i))
if 3<i and i<5:
yield ("编号{},字符串B".format(i))
if i >5:
yield ("编号{},字符串C".format(i))
break
return
with open(r'文本.txt','w') as f:
for i in A_B_ATTACK():
print(''.join(i),file=f)
f= open(r'文本.txt','r')
all_the_text =f.read()
f.close()
def print():
EditText.insert('1.0',all_the_text )
EditText = tk.Text(root,width=30,height=10) #创建文本框
EditText.grid(row=2,column=3)
btn_test=tk.Button(root, text="按钮", command =print,width=5, height=2)
btn_test.place( x=300,y=200)
root.mainloop()
用str.format代替print,然后接收返回的字符串。