Python tkinter:使任何输出出现在 GUI 上的文本框中而不是在 shell 中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14879916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:43:53  来源:igfitidea点击:

Python tkinter: Make any output appear in a text box on GUI not in the shell

pythontkinter

提问by

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?

我正在使用 python 和 tkinter 制作一个 GUI,只是想知道是否有任何输出文本出现在 GUI 的窗口中而不是在解释器/外壳上?

Thanks in advance

提前致谢

回答by James Waldby - jwpat7

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 msinto 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:

如果如 Bryan Oakley 的评论中所建议的那样,您想“在 GUI 中打印 'foo',但让它神奇地出现在文本小部件中”,请参阅上一个问题Python:将 CLI 转换为 GUI 中的答案。这个答案解决了如何在文本框中生成输出的更简单的问题。要生成滚动文本窗口,请创建并放置或打包一个文本小部件(我们称之为mtb),然后使用诸如mtb.insert(Tkinter.END, ms)将字符串添加ms到文本框之类的命令mtb,以及mtb.see(Tkinter.END)使框滚动之类的命令。(有关更多详细信息,请参阅“ The Tkinter Text Widget”文档。)例如:

#!/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 deletemethod at intervals to limit it.

请注意,如果您希望文本窗口长时间保持打开状态和/或积累千兆字节的文本,也许可以跟踪文本框中的数据量,并delete每隔一段时间使用该方法来限制它。