0

I have a slight problem with my code. What I am trying to do is output all of the information from the 'result' variable rather than just the latest entry. I understand that the 'config' method is within the for loop and this is why it is outputting the latest entry but I cannot seem to work out any other way of doing it.

If anyone could help it would be much appreciated.

def view_content(self):
    connection.connect(user="root", password="")
    query = "SELECT * FROM users WHERE User_ID <5"
    cursor.execute(query)
    results = cursor.fetchall()
    for result in results:
        self.answer.config(text=result[0:])

Thanks, Notorious

Notorious
  • 33
  • 2
  • 9

1 Answers1

2

It is only displaying the last row because you overwrite all the other rows of data. Assuming that self.answer is something along the lines of a text area widget that can handle displaying a nested list, you can do something like:

results = cursor.fetchall()
results = '\n'.join(['\t'.join(row) for row in results])
self.answer.config(results)

That middle line converts the the nested list to a tab ('\t') separated string for each line with newlines ('\n') between rows to make it more "human readable" per Bryan Oakley's suggestion.

Another alternative is to setup something to display each row individually and load them approximately how you are currently.

results = cursor.fetchall()
result = results.next()
if result: self.row1.config(text=result)
result = results.next()
if result: self.row2.config(text=result)
result = results.next()
if result: self.row3.config(text=result)
result = results.next()
if result: self.row4.config(text=result)
result = results.next()
if result: self.row5.config(text=result)

An easier way to accomplish that (in general) is to set up a table structure to display that data and add a row to the display table for each row you retrieve. Its been a while,but I don't recall tkinter having a table widget.

Alan Hoover
  • 1,430
  • 2
  • 9
  • 13
  • 1
    I believe that's still true but see here for the usual alternatives https://stackoverflow.com/questions/9348264/does-tkinter-have-a-table-widget – progmatico Apr 02 '18 at 21:27