I am fetching all the rows from MySQL database and trying to get them to print within the textbox
and also using sys.stdout
in my table_frame
.
My printout isn't formatted for spacing properly yet. I'm trying to get the printout into the textbox
first.
I tried to Highlight the code like StackOverflow says to, but it wouldn't highlight the text in the preview. Sorry if it is harder to read. Maybe it will fix itself when it post.
Thanks for any help.
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()
Here is the feedback I am getting.
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 ...?"
Just in case someone else is having this problem I will post the solution that @furas
helped me get.
Original
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)
New - removed
print()
fromresult
and intextbox.insert
changed the index from0
to1.0
. Also, deletedsys.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)