Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating buttons in a grid with Tkinter

I’m trying to get some assistance in a better (more pythonic way) to write this. The intention is to have each row be represented by a button which has the name as its name. To later have clicking the button display the full row information.

def open_file(data_file):
    with open(data_file, 'r+') as f:
        reader = csv.reader(f, delimiter=",")
        next(reader)
        r = 0
        c = 0
        for i in reader:
            button = tk.Button(results, text=i[0], command=lambda: read_ability(data_file, i))
            button.grid(row=r, column=c)
            c += 1
            if (c == 10) and (r == 0):
                r = 1
                c = 0
            elif (c == 10) and (r == 1):
                r = 2
                c = 0
            elif (c == 10) and (r == 2):
                r = 3
                c = 0
            elif (c == 10) and (r == 3):
                r = 4
                c = 0

As you can see, I’ve been manually checking row length before dropping down into the next row for readability. I’m sure there’s a more efficient way. Any advice is very much appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Instead of manually checking what row it is and then incrementing it by 1. You can just check if c == 10 and then directly increment r by 1 using +=.

Improved Code:

def open_file(data_file):
    with open(data_file, 'r+') as f:
        reader = csv.reader(f, delimiter=",")
        next(reader)
        r = 0
        c = 0
        for i in reader:
            button = tk.Button(results, text=i[0], command=lambda: read_ability(data_file, i))
            button.grid(row=r, column=c)
            c += 1
            if c == 10:
                r += 1
                c = 0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading