简体   繁体   中英

How to change text of Tkinter button initilised in a loop

I am trying to create a list of buttons in tkinter that when the button is pressed, change the text in the button from "On" to "Off" and back again.

I can't figure out how to change the text on the buttons as when the tkinter buttons are stored in a list or array they lack the ability to be accessed and changed.

Here is my code

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()

I have tried both arrays and dictionaries, neither work, any help would be appreciated!

I fixed your code.

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()

The main problem was this line:

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) returns None . As a result button dict will hold a None values instead of the references to the button created. Other changes are minor, just to make toggling work and should be easy to understand. Hope it helps.

Second important thing is that in this line you are creating tuples. Tuples are immutable, so cant change 'On'->'Off' and 'Off'->'On' later on. I changed it to a list. This solves the problem of immutability.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM