Tkinter 可变大小列表

Tkinter List of Variable Sizes

我正在尝试使用 Tkinter 制作按钮菜单。我有一个随机生成的文件列表,其属性为元组(名称、大小、Link),需要将它们排列在网格中。由于按钮数量发生变化,我无法将每个按钮设置为网格。以下是我尝试制作的方法:

    def selected_button(file):
        print(f"File: {file[0]}, {file[1]}, Link: {file[2]}")

    for file in files:
        fileButton = Button(root, text= file[0],command= lambda: selected_button(file).grid()`

问题:

如果我遗漏了任何信息,请发表评论,我会及时回复。

问题 #1

要让 lambda 在迭代中存储当前值,需要在 lambda 函数中调用它,例如 command= lambda f = file: selected_button(f).

问题 #2

我通常用来制作按钮网格的方法是选择一个你想要的宽度,可能是 3 宽,然后增加列直到达到那个点。达到该宽度后,重置列并增加行。

import tkinter as tk

# Testing
files = []
for x in range(12):
    files.append((f"Test{x}", f"stuff{x}", f"other{x}"))
# /Testing

def selected_button(file):
    print(f"File: {file[0]}, {file[1]}, Link: {file[2]}")

root = tk.Tk()

r, c = (0,0) # Set the row and column to 0.

c_limit = 3 # Set a limit for how wide the buttons should go.

for file in files:
    tk.Button(root,
              text= file[0],
              width = 20,
              # This will store what is currently in file to f
              # then assign it to the button command.
              command= lambda f=file: selected_button(f)
              ).grid(row = r, column = c)

    c += 1 # increment the column by 1
    if c == c_limit:
        c = 0 # reset the column to 0
        r += 1 # increment the row by 1

root.mainloop()