Python tkinter:使任何输出出现在 GUI 上的文本框中而不是在 shell 中 [英] Python tkinter: Make any output appear in a text box on GUI not in the shell
问题描述
我正在使用 python 和 tkinter 制作一个 GUI,只是想知道是否有任何输出文本出现在 GUI 上的窗口中而不是在解释器/外壳上?
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?
提前致谢
推荐答案
如果,如 Bryan Oakley 的评论中所建议的,您想在 GUI 中打印 'foo',但让它神奇地出现在文本小部件中",请参阅上一个问题的答案 Python:将 CLI 转换为 GUI.这个答案解决了如何在文本框中生成输出的更简单的问题.要生成滚动文本窗口,请创建并放置或打包文本小部件(我们称之为 mtb
),然后使用诸如 mtb.insert(Tkinter.END, ms)
之类的命令将字符串 ms
添加到文本框 mtb
中,并像 mtb.see(Tkinter.END)
使框滚动.(有关更多详细信息,请参阅The Tkinter Text Widget"文档.)例如:
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()
请注意,如果您希望文本窗口长时间保持打开状态和/或积累千兆字节的文本,也许可以跟踪文本框中的数据量,并使用 delete
方法每隔一段时间来限制它.
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.
这篇关于Python tkinter:使任何输出出现在 GUI 上的文本框中而不是在 shell 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!