【问题标题】:Tkinter List of Variable SizesTkinter 可变大小列表
【发布时间】:2020-04-14 19:05:29
【问题描述】:

我正在尝试使用 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()`

问题:

  • 在单击按钮时传递的变量“文件”始终是最后生成的按钮。
  • 按钮将它们自己排列成一列中的长列表 - 我需要一个漂亮的正方形/矩形。

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

【问题讨论】:

  • “我无法将每个按钮设置为网格,因为按钮的数量会发生变化。” 这没有多大意义。 tkinter 中没有任何东西可以阻止您这样做。另外,您说您需要一个“漂亮的正方形/矩形”。如果是这样的话,你为什么不使用grid 的参数?它允许您指定行和列。

标签: python database user-interface tkinter menu


【解决方案1】:

问题 #1

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

问题 #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()

【讨论】:

    猜你喜欢
    • 2011-08-17
    • 2017-11-03
    • 2023-04-08
    • 2019-09-21
    • 2013-04-23
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    • 2011-04-20
    相关资源
    最近更新 更多