Home > Blockchain >  Creating buttons in a grid with Tkinter
Creating buttons in a grid with Tkinter

Time:04-14

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.

CodePudding user response:

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
  • Related