如何更改在循环中初始化的 Tkinter 按钮的文本

How to change text of Tkinter button initilised in a loop

我正在尝试在 tkinter 中创建一个按钮列表,当按下按钮时,将按钮中的文本从 "On" 更改为 "Off" 然后再更改回来。

我不知道如何更改按钮上的文本,因为当 tkinter 按钮存储在列表或数组中时,它们无法访问和更改。

这是我的代码

import Tkinter as tk

button = {}

def toggle_text(button_number):

    print(button_number)

    if (button[button_number][1] == "On"):
        button.configure(text = "Coil %d is Off" %button_number)
    else: 
        button.configure(text = "Coil %d is On" %button_number)

root = tk.Tk()
root.title("Click the Buttons to change the state of the coil")

for i in range(1,13):

    button[i]  = tk.Button(text="Coil %d is On" %i , width=50, command=lambda i=i: toggle_text(i)).grid(row = i, column = 1), "Off"

root.mainloop()

数组和字典我都试过了,都不行,如有帮助,将不胜感激!

我修复了你的代码。

import Tkinter as tk



button = {}

def toggle_text(button_number):
    print(button_number)

    if (button[button_number][1] == "On"):
        button[button_number][0].configure(text = "Coil %d is Off" %button_number)
        button[button_number][1]='Off'
    else:         
        button[button_number][0].configure(text = "Coil %d is On" % button_number)
        button[button_number][1]='On'


root = tk.Tk()
root.title("Click the Buttons to change the state of the coil")

for i in range(1,13):
    button[i]  = [tk.Button(text="Coil %d is On" %i , 
                           width=50, 
                           command=lambda i=i: toggle_text(i)), "On"]
    button[i][0].grid(row = i, column = 1)


root.mainloop()

主要问题是这一行:

button[i]  = tk.Button(text="Coil %d is On" %i , width=50, command=lambda i=i: toggle_text(i)).grid(row = i, column = 1), "Off"

grid(row = i, column = 1)returnsNone。结果,按钮字典将保存 None 值,而不是对创建的按钮的引用。其他更改很小,只是为了使切换工作并且应该易于理解。希望对你有帮助。

第二个重要的事情是在这一行中你正在创建元组。元组是不可变的,因此以后不能更改 'On'->'Off' 和 'Off'->'On'。我把它改成了一个列表。这解决了不变性问题。