我想用文本框将 Python shell 的输出重定向到我的 Tkinter GUI。
例如,在我的游戏中单击 Inventory 将在 Python shell 中显示您的耗材。我希望它显示在 GUI 文本框中。
我该怎么做呢?
我想用文本框将 Python shell 的输出重定向到我的 Tkinter GUI。
例如,在我的游戏中单击 Inventory 将在 Python shell 中显示您的耗材。我希望它显示在 GUI 文本框中。
我该怎么做呢?
您可以为您的文本框创建一个处理程序,以便:
class textbox_handler:
def __init__(self, text):
self.data = []
self.text = text #text is your tk text widget.
def write(self, s):
self.data.append(s)
def print_out(self):
for line in data:
self.text.insert('end',line)
然后,在您的主要功能中:
import sys
def main():
handler = textbox_handler(text1)
sys.stdout = handler
print "sample text."
print "sample text #2."
print "another sample text."
#or you can use without setting sys.stdout
print >>handler, "yet another sample text."
每个打印语句调用处理程序对象的 write 方法。您可以简单地从 handler.data 中检索这些字符串。