Python 将print()的输出发送到tkinter文本小部件
我编写了一个Python3.4.2程序,从PythonIdle获取用户输入,对输入执行一些处理,并使用print()在PythonIdle中显示一些语句 现在我正在使用tkinter将其转换为GUI。这是我为GUI编写的简单tkinter代码Python 将print()的输出发送到tkinter文本小部件,python,user-interface,tkinter,Python,User Interface,Tkinter,我编写了一个Python3.4.2程序,从PythonIdle获取用户输入,对输入执行一些处理,并使用print()在PythonIdle中显示一些语句 现在我正在使用tkinter将其转换为GUI。这是我为GUI编写的简单tkinter代码 from tkinter import * root=Tk() root.title("Post-fix solver") root.geometry("500x500") mainframe=Frame(root) mainframe.grid(colu
from tkinter import *
root=Tk()
root.title("Post-fix solver")
root.geometry("500x500")
mainframe=Frame(root)
mainframe.grid(column=0, row=0)
inputval=StringVar()
inputentry=Entry(mainframe,textvariable=inputval).grid(column=1,row=1)
executebutton=Button(mainframe,text="Run",command=check_expression).grid(column=1,row=5)
outputtext=Text(mainframe).grid(column=1,row=5)
root.mainloop()
到目前为止,我能够通过GUI中名为inputentry的条目小部件获取用户输入,并使用inputval.get()将其发送到原始代码中的变量。然后它对输入执行处理,并在python IDLE中显示print()语句的输出
我的问题是如何修改程序,将所有这些print()语句发送到名为outputtext的文本小部件,并在GUI中显示它们
如果您能告诉我如何在不使用类的情况下执行此操作,我将非常高兴,因为我是python的初学者如果您也使用python 3.4+来运行该程序,您可以使用将打印输出捕获到一个文件中,甚至一个字符串中:
import io
from contextlib import redirect_stdout
...
file = io.StringIO()
with redirect_stdout(file):
# here be all the commands whose print output
# we want to capture.
output = file.getvalue()
# output is a `str` whose contents is everything that was
# printed within the above with block.
否则,一个更好但有点困难的方法是制作一个
StringIO
文件并打印到其中,这样您就可以
buffer = io.StringIO()
print("something", file=buffer)
print("something more", file=buffer)
output = buffer.getvalue()
text.insert(END, output)
3个简单步骤:
1) 获取变量的内容并将其放入我将命名为varContent
的变量中2) 清除文本小部件,即如果文本小部件的名称为
text
,则运行text.delete(0,END)
3) 将变量
varContent
中的字符串插入text
text小部件,即执行text.Insert(END,varContent)
我会这样编写代码:
from tkinter import *
def check_expression():
#Your code that checks the expression
varContent = inputentry.get() # get what's written in the inputentry entry widget
outputtext.delete('0', 'end-1c') # clear the outputtext text widget
outputtext.insert(varContent)
root = Tk()
root.title("Post-fix solver")
root.geometry("500x500")
mainframe = Frame(root)
mainframe.grid(column=0, row=0)
inputentry = Entry(mainframe)
inputentry.grid(column=1, row=1)
executebutton = Button(mainframe, text="Run", command=check_expression)
executebutton.grid(column=1, row=5)
outputtext = Text(mainframe)
outputtext.grid(column=1, row=5)
root.mainloop()
用于Python 3.x 使用
inpuntery=entry(mainframe.grid()
创建输入框后,可以使用inpuntery.get()
获取键入的条目
执行以下操作将键入的条目放入变量中,并在名为outputtext
的文本小部件中打印它:
entryvar=inputentry.get() # the variable entryvar contains the text widget content
outputtext.delete(1.0,tk.END) # clear the outputtext text widget. 1.0 and tk.END are neccessary. tk implies the tkinter module. If you just want to add text dont incude that line
outputtext.insert(tk.END,entryvar) # insert the entry widget contents in the text widget. tk.END is necessary.
可能重复的