Python 如何为按钮创建一个网格,给它们一个名称(即使我用“for”创建它们)

Python 如何为按钮创建一个网格,给它们一个名称(即使我用“for”创建它们),python,tkinter,Python,Tkinter,我最近看到一个关于“如何制作大小自动变化的按钮网格”的问题。我在那里发现了一个非常有趣的代码示例,但是,建议的方法在“for”中创建了按钮,这不允许将它们设置为特定参数。以下是代码: frame = Frame(root) Grid.rowconfigure(root, 0, weight = 1) Grid.columnconfigure(root, 0, weight = 1) frame.grid(row = 0, column = 0, sticky = N + S + E + W) g

我最近看到一个关于“如何制作大小自动变化的按钮网格”的问题。我在那里发现了一个非常有趣的代码示例,但是,建议的方法在“for”中创建了按钮,这不允许将它们设置为特定参数。以下是代码:

frame = Frame(root)
Grid.rowconfigure(root, 0, weight = 1)
Grid.columnconfigure(root, 0, weight = 1)
frame.grid(row = 0, column = 0, sticky = N + S + E + W)
grid = Frame(frame)
grid.grid(sticky = N + S + E + W, column = 0, row = 7, columnspan = 2)
Grid.rowconfigure(frame, 7, weight = 1)
Grid.columnconfigure(frame, 0, weight = 1)

for x in range(10):
    for y in range(5):
        btn = Button(frame)
        btn.grid(column = x, row = y, sticky = N + S + E + W)

for x in range(10):
    Grid.columnconfigure(frame, x, weight = 1)

for y in range(5):
    Grid.rowconfigure(frame, y, weight = 1)

您能告诉我如何使每个按钮不同吗?

我在这里看到的一个问题是您将tkinter作为tk导入,但在尝试设置框架或按钮时不要使用前缀
tk.
。这使我相信您可能也在使用tkinter import*执行
,这是一个非常糟糕的主意,尤其是当您编写
grid=Frame(root)
时,因为在实际尝试使用
grid()
之前,您将覆盖
grid()
方法一行

通过使用按钮列表,我们可以引用存储按钮的索引并对其进行处理

请参阅下面的示例,如果您有任何问题,请告诉我:

import tkinter as tk


def some_function(ndex):
    print(button_list[ndex]['text'])
    button_list[ndex].config(text='', background='black')
    print(button_list[ndex]['text'])


root = tk.Tk()
root.geometry('300x200')
button_list = []

for x in range(15):
    root.columnconfigure(x, weight=1)
    for y in range(17):
        button_list.append(tk.Button(root))
        count = len(button_list)
        button_list[-1].config(text='{}'.format(count), command=lambda ndex=count-1: some_function(ndex))
        button_list[-1].grid(column=x, row=y, sticky='nsew')
        if x == 0:
            root.rowconfigure(y, weight=1)


root.mainloop()
为了好玩和即将到来的假期,这里有一个由代码D制成的杰克灯

要回答评论中的问题,请参见以下代码:

import tkinter as tk


def some_function(value):
    print(value)


root = tk.Tk()
button_values = [['A', 'B', 'C'], ['=', '+', '-']]
button_list = []

for ndex, sub_list in enumerate(button_values):
    root.columnconfigure(ndex, weight=1)
    for sub_ndex, value in enumerate(sub_list):
        button_list.append(tk.Button(root))
        count = len(button_list)
        button_list[-1].config(text=value, command=lambda x=value: some_function(x))
        button_list[-1].grid(column=ndex, row=sub_ndex, sticky='nsew')


root.mainloop()
结果:

按下每个按钮后的控制台:

A
B
C
=
+
-

你说的“使每个按钮都不同”是什么意思?你在寻找什么样的差异?颜色字体?大小?您需要的是按钮列表,而不是每个按钮的名称。使用列表,您可以引用索引来更新按钮。@BryanOakley我正在查找文本和命令的差异。您好。谢谢你的回答。如果我想精确地为每个按钮设置不同的文本或命令,该怎么办?例如,我想让右下角的按钮成为“=”,当我点击它时会发送结果…这很简单。我们只是把你想要的所有按钮列成一个列表,然后用这个列表和索引号来制作你的按钮。@Bethoth我在我的答案中添加了一个例子。唯一的一件事我仍然不明白的是如何给每个按钮一个不同的命令……如果你想动态地做这件事,你只需引用列表中与你的需要。就像你在做计算器一样。要实现这一点,您需要使用一个名为lmabda的无名函数。这允许您编写可以用作命令的单行函数。下面是一个例子,他们这样做是为了制作一种屏幕键盘。