首页 > 解决方案 > 如何更新为 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()

标签: pythontkinter

解决方案


您使用的 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)

推荐阅读