我正在尝试使用Tkinter制作按钮菜单。我有一个随机生成的文件列表,其属性为元组(名称,大小,链接),需要将它们排列在网格中。由于按钮的数量已更改,因此无法将每个按钮设置为网格。这是我尝试的方法:
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)
。
问题二
我通常用于制作按钮网格的方法是选择所需的宽度(可能为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()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句