我如何循环遍历按钮并将它们自动放置在网格中?

huangapple go评论72阅读模式
英文:

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)

我如何循环遍历按钮并将它们自动放置在网格中?

huangapple
  • 本文由 发表于 2023年5月14日 22:10:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76247906.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定