gpt4 book ai didi

python - Tkinter 复选框拆分列表

转载 作者:太空宇宙 更新时间:2023-11-03 21:34:56 27 4
gpt4 key购买 nike

我正在尝试将包含 ~ 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

非常感谢您的帮助

最佳答案

使用计数器和网格几何管理器将使您的生活变得更加轻松。您可以看到 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

关于python - Tkinter 复选框拆分列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53290993/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com