how can we redirect the output of the button action to TextBox in Tkinter? And after that TextBox should be grayed out. Here is the sample code I have written which prints the output on the console. I want "hello world" to be printed in the textbox and textbox should be grayed out. Any help would be appreciated.
from tkinter import *
import tkinter as tk
root = Tk()
root.geometry('700x650')
readOnlyText = tk.Text(root)
def testmethod():
print("hello world-1")
textbox = Text(root,width=75,height=12)
textbox.place(x=60,y=100)
Button(root, text='Submit',command=testmethod,width=10,bg='brown',fg='white').place(x=300,y=350)
root.mainloop()
To intercept the print
function, you will need to change the sys.stdout
target. Refer to the example below
from tkinter import *
from io import StringIO
import sys
root = Tk()
root.geometry('700x650')
output=StringIO()
sys.stdout=output
def update():
textbox['state']='normal'
textbox.insert(END,output.getvalue())
output.truncate(0)
output.seek(0)
textbox['state']='disabled'
root.after(100,update)
def testmethod():
print('Hello World')
textbox = Text(root,width=75,height=12)
textbox.place(x=60,y=100)
button=Button(root, text='Submit',command=testmethod,width=10,bg='brown',fg='white')
button.place(x=300,y=350)
update()
root.mainloop()
The update
function will be called after every 100
milliseconds, which will insert the current value held by output
and then clear it. The state
of the Text
widget should be normal
to make any changes to its contents, hence the state
has been toggled in every call.
To restore the output back to the shell, you can call
sys.stdout = sys.__stdout__
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.