如何在Tkinter中更新为列表创建的按钮的文本

时间:2020-09-04 04:52:44

标签: 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()

2 个答案:

答案 0 :(得分:1)

您使用的FOR循环最终会将'btn'变量更改为带有'button 3 available'文本的按钮。 我对此的解决方案是创建另一个创建单个按钮的功能:

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)

答案 1 :(得分:0)

这应该可以满足您的需求。

from tkinter import *

root = Tk()

buttonTextList = ["button 1 available", "button 2 available", "button 3 available"]

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 buttonTextList: 
    createButton(item)