[英]How to update text of buttons created for a list in 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”變量更改為帶有“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)
這應該可以滿足您的需求。
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.