I am making a GUI using python and tkinter and just wondering if there is anyway to make any output text appear in a window on the GUI not on the interpreter/shell?
If, as suggested in Bryan Oakley's comment, you want to “print 'foo' in your GUI, but have it magically appear in the text widget”, see answers in previous question Python : Converting CLI to GUI. This answer addresses the simpler issue of how to produce output in a text box. To produce a scrolling text window, create and place or pack a text widget (let's call it mtb
), then use commands like mtb.insert(Tkinter.END, ms)
to add string ms
into text box mtb
, and like mtb.see(Tkinter.END)
to make the box scroll. (See “The Tkinter Text Widget” documentation for more details.) For example:
#!/usr/bin/env python
import Tkinter as tk
def cbc(id, tex):
return lambda : callback(id, tex)
def callback(id, tex):
s = 'At {} f is {}\n'.format(id, id**id/0.987)
tex.insert(tk.END, s)
tex.see(tk.END) # Scroll if necessary
top = tk.Tk()
tex = tk.Text(master=top)
tex.pack(side=tk.RIGHT)
bop = tk.Frame()
bop.pack(side=tk.LEFT)
for k in range(1,10):
tv = 'Say {}'.format(k)
b = tk.Button(bop, text=tv, command=cbc(k, tex))
b.pack()
tk.Button(bop, text='Exit', command=top.destroy).pack()
top.mainloop()
Note, if you expect the text window to stay open for long periods and/or accumulate gigabytes of text, perhaps keep track of how much data is in the text box, and use the delete
method at intervals to limit it.