在tkinter文本框中显示Python的print()函数的输出,可以通过以下步骤实现:
import tkinter as tk
root = tk.Tk()
text_box = tk.Text(root)
def redirect_print(*args, **kwargs):
output = ""
for arg in args:
output += str(arg) + " "
text_box.insert(tk.END, output + "\n")
text_box.see(tk.END) # 滚动到文本框底部
# 重定向print()函数的输出
print = redirect_print
text_box.pack()
root.mainloop()
完整的代码示例:
import tkinter as tk
def redirect_print(*args, **kwargs):
output = ""
for arg in args:
output += str(arg) + " "
text_box.insert(tk.END, output + "\n")
text_box.see(tk.END) # 滚动到文本框底部
root = tk.Tk()
text_box = tk.Text(root)
text_box.pack()
# 重定向print()函数的输出
print = redirect_print
# 测试输出
print("Hello, World!")
print("This is a test.")
root.mainloop()
这样,当你使用print()函数输出内容时,输出将会显示在tkinter文本框中。
领取专属 10元无门槛券
手把手带您无忧上云