0

I have created a MySQL database with a users name, score, and date. I want to pack 10 rows of data on to a tkinter box I have made, however I do not know the best way of doing this. I have tried making the information a label:

def print_result():
global other_information
other_information = 3
myresult = mycursor.fetchall()
for result in myresult:
    global result_label
    result_label = Label(text=result)
    result_label.pack()
back_radio.pack()

and while this successfully packs the rows of data on the tkinter box, when I try pack_forget(), only the final row unpacks and the rest of the data is left on the tkinter box. This is my code for unpacking:

elif other_information == 3:
result_label.pack_forget()
back_radio.pack_forget()
display()

So I decided to try put it in a text widget:

def print_result():
    myresult = mycursor.fetchall()
    for result in myresult:
        global result_text
        result_text = Text(game, height=300, width=300)
        result_text.insert('1.0', result)
        result_text.pack()
    back_radio.pack()

However this only packed one row of data, and my radio buttons would not show up. What is the best way to display the rows of data on a tkinter box and how would I unpack it?

Thanks!

  • ***"the best way"***: Depends at what you want? Not the best, but **one** possible solution: [pretty-print-data-in-tkinter-label](https://stackoverflow.com/questions/58658656/pretty-print-data-in-tkinter-label) – stovfl Nov 02 '19 at 08:23

1 Answers1

0

If you want to show result of a query onto a tkinter gui then you can just use Scrolledtext(preferably) or any other Text widget and insert the result onto it. You can form tabular data from the fetched result of a query using a simple module named tabulate. Use the below for reference-

from tabulate import tabulate
import tkinter as tk
from tkinter.scrolledtext import ScrolledText

class Root(tk.Tk):
    fetch_data = [(None, 21, 20, 20, 20, 20), (8, None, 8, 8, 8, 8)]
    fetch_col = ['TEACHER', 'STUDENT', 'A', 'B', 'C', 'D']
    def __init__(self):
        super().__init__()

        h_scrlbar = tk.Scrollbar(self, orient='horizontal')
        h_scrlbar.pack(side='bottom', fill='x')

        self.res_tbl = ScrolledText(self, font=(
            'Consolas', 14), wrap='none', xscrollcommand=h_scrlbar.set)
        self.res_tbl.pack(fill='both', expand=1)
        h_scrlbar.config(command=self.res_tbl.xview)

        pr = tabulate(Root.fetch_data, Root.fetch_col, tablefmt='psql', missingval='-')
        self.res_tbl.insert(0.0, pr)

if __name__ == '__main__':
    Root().mainloop()

Where fetch_data & fetch_col can instead be obtained from the sql query result.