Tkinter复选框拆分列表

2024-06-09 13:57:46 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我尝试将第一个文件拆分为最多10个项目的文件,并在框架中创建新的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

非常感谢你的帮助


Tags: 文件path项目textselftxtforinit
1条回答
网友
1楼 · 发布于 2024-06-09 13:57:46

使用计数器和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

相关问题 更多 >