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

时间:2015-02-16 01:00:53

标签: python button tkinter

我正在尝试在tkinter中创建一个按钮列表,当按下按钮时,更改按钮中的文本,从" On"到"关"又回来了。

我无法弄清楚如何更改按钮上的文字,因为当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()

我已经尝试了数组和词典,但都没有工作,任何帮助都会受到赞赏!

1 个答案:

答案 0 :(得分:2)

我修复了你的代码。

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)返回None。因此,按钮dict将保持None值,而不是对创建的按钮的引用。其他变化很小,只是为了进行切换工作,应该很容易理解。希望它有所帮助。

第二个重要的是,在这一行中你创建了元组。元组是不可改变的,因此无法改变' On' - >' Off'和'关闭' - >'开启'稍后的。我把它改成了一个清单。这解决了不变性问题。