【问题标题】:Tkinter checkbox split listTkinter 复选框拆分列表
【发布时间】:2019-04-16 21:01:12
【问题描述】:

我正在尝试将列表从包含 ~ 100 个项目的文件拆分为多行复选框(每行 10 个 ~)。因为所有项目都在同一条长线上。

我尝试将第一个文件拆分为最多包含 10 个项目的 nFiles,并在框架中创建新的检查按钮行。 但没办法,我只得到了同一行中的所有项目:

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

非常感谢您的帮助

【问题讨论】:

    标签: python list checkbox tkinter split


    【解决方案1】:

    使用计数器和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 个项目的文件。它适用于任意数量的文件。试试看吧。

    【讨论】:

    • @Indi59 很高兴我能帮上忙。
    猜你喜欢
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2015-03-19
    • 2012-12-30
    • 1970-01-01
    • 2019-06-12
    相关资源
    最近更新 更多