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

如何在Tkinter中通过按钮将输入框内容追加到列表?点击按钮后列表仍为空的问题求助

问题排查与解决方案

我帮你梳理了代码里的问题,点击按钮后列表为空主要是两个关键错误导致的:

1. Entry控件的赋值逻辑错误

你写的entry = tk.Entry(fg="white", bg="black", width=50 ).pack()其实把pack()方法的返回值(也就是None)赋给了entry变量,而不是实际的Entry控件对象。pack()是布局方法,它不会返回控件本身,必须把创建控件和布局操作分开写:

entry = tk.Entry(fg="white", bg="black", width=50 )
entry.pack()

2. 未获取输入框的文本内容

你的btn1()函数里直接把entry(之前是None,就算改对了也是控件对象)追加到列表,而不是输入框里的用户输入文本。要获取输入框内容,需要调用Entry控件的get()方法:

def btn1():
    input_text = entry.get()
    if input_text:  # 可以加个判断,避免追加空字符串
        y.append(input_text)
        print("当前列表内容:", y)  # 打印列表,方便验证是否添加成功

修正后的完整代码

我还清理了代码里冗余的导入模块和无用函数,同时给窗口添加了黑色背景让界面更协调:

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from decimal import Decimal
import random
import tkinter as tk

y = []
root = tk.Tk()
root.configure(background="black")

label = tk.Label(text="WhatsApp Spam", foreground="white", background="black")
label.pack()

creator = tk.Label(text="creator : BlonDie", foreground="yellow", background="black")
creator.pack()

discreption = tk.Label(
    text="to use app : \n1: type your input \n2: open app \n3:login your whatsapp \n4: select your contact \n5: till you close this app it will send that massage",
    foreground="white", background="black"
)
discreption.pack()

# 修正Entry的创建与布局
entry = tk.Entry(fg="white", bg="black", width=50 )
entry.pack()

def btn1():
    input_text = entry.get()
    if input_text:
        y.append(input_text)
        print("当前列表内容:", y)  # 验证用的打印

tk.Button(text="start", command=btn1, fg="white", bg="black").pack()

root.mainloop()

现在点击"start"按钮后,输入框里的文本就会被正确追加到列表y中了,你可以通过控制台的打印信息确认添加结果。

内容的提问来源于stack exchange,提问作者اریا صابری ار ام

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 20:07:46