You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现点击tkinter网格按钮时将按钮文本存入数组?

问题解决:点击按钮仅添加对应文字到数组

问题根源

  • 你给按钮的command参数赋值时,直接写了list.append(Word[w][a]),这行代码会在创建按钮的瞬间就执行,而非用户点击按钮时触发,所以所有按钮的文字一开始就被塞进数组了。
  • 另外,别用list当变量名,这是Python内置类型,会覆盖原有功能,建议换成selected_words这类名字。

解决方案

要实现点击按钮才执行添加操作,得用lambda表达式绑定对应文字,确保只有点击动作触发时才调用append方法。

以下是修正后的完整代码:

import tkinter as tk
from tkinter import *
from tkinter import ttk


root = tk.Tk()
# 替换list为selected_words,避免覆盖内置类型
selected_words = []
root.title("grid() method")
root.geometry("390x844") 
frame = tk.Frame(root, bg="white")
frame.place(relwidth=390,relheight=844)

# 按钮文字列表
Word =[['Adventurous', 'Creative', 'Artistic', "Curious", "Abstract"],
    ["Self-Disciplined", "Organized", "Plan-Driven", "Aware", "Detail Focused"],
    ["Energetic", "Center of Attention", "Assertive", "Impulsive", "Sociable"],
    ["Empathetic", "Trusting", "Honest", "Helping", "Put others first"],
    ["Stress Easy", "Moody", "Worrisome", "Emotionally Unstable", "Irritable"]]

# 创建按钮网格
for w in range(len(Word)):
    # 改用len(Word[w])适配子列表长度不一致的情况,更健壮
    for a in range(len(Word[w])):  
        button1 = tk.Button(root, height=4, width=5, bd=6, padx=18.50, pady=18.50)
        button1.grid(row=w, column=a)
        # 用lambda绑定当前按钮的文字,确保点击时才执行添加
        button1.config(
            text=Word[w][a], 
            justify=LEFT, 
            command=lambda word=Word[w][a]: selected_words.append(word)
        )
        
root.mainloop()
print(selected_words)

关键修改说明

  1. 变量名替换:把list改成selected_words,避免和Python内置的list类型冲突。
  2. lambda绑定参数:lambda word=Word[w][a]: selected_words.append(word)会将当前循环的按钮文字绑定到lambda的参数word上,每个按钮的command都对应自己的文字,点击时才会执行添加操作。
  3. 循环范围优化:将内层循环的range(len(Word))改为range(len(Word[w])),如果后续Word的子列表长度不同,代码也能正常运行。

修改后,只有点击对应按钮时,按钮上的文字才会被添加到数组中。

内容的提问来源于stack exchange,提问作者chanu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 00:05:26