使用 Tkinter 在网格中创建按钮

Creating buttons in a grid with Tkinter

我正在尝试以更好的(更像 Python 的方式)获得一些帮助来编写此代码。目的是让每一行都由一个名称作为名称的按钮表示。稍后单击按钮显示整行信息。

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

如您所见,我一直在手动检查行的长度,然后再放入下一行以提高可读性。我相信有一种更有效的方法。非常感谢任何建议。

无需手动检查它是哪一行,然后将其递增 1。您可以只检查 c == 10,然后使用 += 直接将 r 递增 1。

改进代码:

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