Tkinter复选框拆分列表

时间:2018-11-13 23:26:47

标签: python list checkbox tkinter split

我正在尝试将列表从一个文件中分离出来,该文件包含约100个项目,并分成多行复选框(每行10个)。因为所有项目都在同一行上。

我试图将第一个文件拆分为最大10个项目的nFiles,并在框架中创建新的checkbutton行。 但是没有办法,我只能在同一行中找到所有项目:

class DisplayApp(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("My Menu")
        frame_1 = tk.LabelFrame(self, text="Frame 1")
        frame_1.grid(row=2, columnspan=3, sticky='WE', padx=5, pady=5, ipadx=5, ipady=5)
        path = '/home/lst/*.txt'
        files=glob.glob(path)
        for file in files:
            with open(file, 'r') as lst_file:
                for item in lst_file:
                    tk.Checkbutton(frame_1, text=item.rstrip()).pack(side=tk.LEFT)

if __name__ == "__main__":
    DisplayApp().mainloop()

初始txt文件:

item1 
item2
item3
...
item100

非常感谢您的帮助

1 个答案:

答案 0 :(得分:0)

使用计数器和grid几何管理器将使您的生活更加轻松。您可以看到count变量如何指示Checkbutton在框架中的行和列。看一下代码。

import tkinter as tk
import glob

class DisplayApp(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("My Menu")
        frame_1 = tk.LabelFrame(self, text="Frame 1")
        frame_1.grid(row=0, sticky='ew', padx=5, pady=5, ipadx=5, ipady=5)
        path = '/path/to/your/txt/files'
        files=glob.glob(path)
        count = 0
        for file in files:
            with open(file, 'r') as lst_file:
                for item in lst_file:
                    tk.Checkbutton(frame_1, text=item.rstrip()).grid(row=count//10, column=count%10)
                    count += 1

if __name__ == "__main__":
    DisplayApp().mainloop()

我有一个包含30个项目的文件。它可以处理任意数量的文件。试试看。

enter image description here