如何获取sys.stdout以将结果打印到tkinter GUI文本框中

时间:2019-04-18 02:34:43

标签: python tkinter textbox

我正在从MySQL数据库中获取所有行,并尝试使其在textbox中打印,并且还在我的sys.stdout中使用table_frame。 我的打印输出尚未格式化,无法正确设置间距。我正在尝试先将打印输出放入textbox

我试图像StackOverflow所说的那样突出显示代码,但不会突出显示预览中的文本。抱歉,如果难以阅读。也许它会在发布时自行修复。

感谢您的帮助。

from tkinter import *
import tkinter.messagebox
import mysql.connector

#  ======================MySQL Connection================================================================

mydb = mysql.connector.connect(
    host = "localhost",
    user = "root",
    passwd = "<INSERT PASSWORD>",
    database = "testdb",
    )

# Create Cursor Instance
my_cursor = mydb.cursor()

table_frame = Frame(root, width=500, height=140, bg='yellow')
table_frame.pack(side=TOP)


textbox=Text(table_frame)
textbox.pack()
row = []

def inv_row_print():
    print("Item Code\tBrand\t\tUnits\t\tIn Stock\t\tUnit Cost")
    my_cursor.execute("SELECT * FROM trialprojectdb.inventory")
    all_rows = my_cursor.fetchall()

    for row in all_rows:
        result = print("{0}\t\t{1}\t\t{2}\t\t{3}\t\t{4}".format(row[0], row[1], row[2],
                 row[3], row[4]))
        textbox.insert(0, result)
sys.stdout.write = inv_row_print() 


btn2 = Button(btm_frame, text='Show Table', command = lambda : inv_row_print())
btn2.place(x=200,y=90)


root.mainloop()

这是我得到的反馈。

Item Code       Brand           Units           In Stock                Unit Cost
1               M&M Peanut              62              None            9.98
Traceback (most recent call last):
  File "Import_Test_Code2.py", line 124, in <module>
    sys.stdout.write = inv_row_print()
  File "Import_Test_Code2.py", line 123, in inv_row_print
    textbox.insert(0, result)
  File "C:\Users\darre\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 3269, in insert
    self.tk.call((self._w, 'insert', index, chars) + args)
_tkinter.TclError: wrong # args: should be ".!frame3.!text insert index chars ?tagList chars tagList ...?"

1 个答案:

答案 0 :(得分:1)

以防万一其他人遇到此问题,我将发布@furas帮助我获得解决方案。

  

原始

for row in all_rows:
        result = print("{0}\t\t{1}\t\t{2}\t\t{3}\t\t{4}".format(row[0], row[1], row[2],
                 row[3], row[4]))
        textbox.insert(0, result)
  

新功能-从print()中删除了result,并在textbox.insert中将索引从0更改为1.0。另外,删除了sys.stdout.write = inv_row_print()

for row in all_rows:
        result = "{0}\t\t{1}\t\t{2}\t\t{3}\t\t{4}".format(row[0], row[1], row[2], 
                  row[3], row[4])
        textbox.insert(1.0, result)