英文:
How can i loop through buttons and place them automatically in a grid?
问题
以下是您提供的代码的翻译:
import customtkinter as ctk
class App(ctk.CTk):
def __init__(self):
super().__init__()
self.title('搜索栏')
self.geometry('500x500')
self.resizable(False, False)
self.items = ['项目1', '项目2', '项目3', '项目4', '项目5', '项目6', '项目7', '项目8', '项目10', '项目11', '项目12']
self.frame = ctk.CTkFrame(self)
self.frame.pack(pady=5, padx=5, fill='both', expand=True)
def update(self, data):
for item in data:
button = ctk.CTkButton(self.frame, text=item, width=50, height=50)
button.pack()
if __name__ == '__main__':
app = App()
app.update(app.items)
app.mainloop()
这是您想要的翻译。
英文:
This is the code:
import customtkinter as ctk
class App(ctk.CTk):
def __init__(self):
super().__init__()
self.title('Searchbar')
self.geometry('500x500')
self.resizable(False, False)
self.items = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item10', 'item11', 'item12']
self.frame = ctk.CTkFrame(self)
self.frame.pack(pady=5, padx=5, fill='both', expand=True)
def update(self, data):
for item in data:
button = ctk.CTkButton(self.frame, text=item, width=50, height=50)
button.pack()
if __name__ == '__main__':
app = App()
app.update(app.items)
app.mainloop()
this is what i get:
but this is what i want: (don't mind the edit..)
I haven't tried anything since i don't know the solution.
答案1
得分: 2
你可以使用enumerate()
函数从列表中获取索引和项目,然后使用索引确定要放置按钮的行和列:
def update(self, data):
for i, item in enumerate(data):
# 每行8列
行, 列 = divmod(i, 8)
按钮 = ctk.CTkButton(self.frame, text=item, width=50, height=50)
按钮.grid(row=行, column=列, sticky="ew", padx=5, pady=5)
英文:
You can use the enumerate()
function to get the index and the item from a list and then use the index to determine the row and column to be used to put the button:
def update(self, data):
for i, item in enumerate(data):
# 8 columns per row
row, col = divmod(i, 8)
button = ctk.CTkButton(self.frame, text=item, width=50, height=50)
button.grid(row=row, column=col, sticky="ew", padx=5, pady=5)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论