python - 如何更新为 tkinter 中的列表创建的按钮的文本
问题描述
使用 for 循环创建按钮列表,当单击按钮时,它的文本会更新为“不可用”。我下面的代码只会更新最新的按钮,而不是指定的那个
from tkinter import *
root = Tk()
list = ["button 1 available", "button 2 available", "button 3 available"]
def update(item):
btn["text"] = item.replace("available", "unavailable")
for item in list:
btn = Button(root, text=item, command=lambda : update(item))
btn.pack()
root.mainloop()
解决方案
您使用的 FOR 循环最终会将“btn”变量更改为带有“按钮 3 可用”文本的按钮。我的解决方案是创建另一个创建单个按钮的函数:
from tkinter import *
root = Tk()
list = ["button 1 available", "button 2 available", "button 3 available"]
# Function to change button text
def update(item, btn):
btn["text"] = item.replace("available", "unavailable")
# Function to create button
def createButton(item):
btn = Button(root, text=item, command=lambda: update(item, btn))
btn.pack()
# Updated for loop
for item in list:
createButton(item)
推荐阅读
- android - 使用“慢速测试卡。几分钟后拒绝”的 Android BillingClient 购买仍处于待处理状态
- android - 使用导航组件的多个后退堆栈 - 如何始终转到特定底部导航选项卡的起始目的地?
- snakemake - InputFunctionException - 扩展和输入函数未解析通配符
- javascript - 为什么我不能在主要功能中编写 console.log
- c# - 是否可以不绑定到元素的属性,而是绑定到 WPF 中的元素本身?
- node.js - 从 Heroku 向 Firebase 进行身份验证错误:找不到模块
- php - 替换数组中所有在php中具有“o”字母的值
- amazon-web-services - Amplify (AWS) 验证电子邮件给出 400 错误请求错误
- javascript - 关于对象上的 ES6 扩展运算符的快速问题
- azure-devops - 利用变量填充 kubernetesServiceConnection:在 KubernetesManifest@0 任务中设置