这是我困惑的代码
from tkinter import *
root = Tk()
root.geometry("100x200")
def changeOne():
if B.config('text')[-1] == "ITE 003":
B.config(text="Hello", fg="red")
else:
B.config(text="ITE 003", fg ="green")
def changeTwo():
if label.config('text')[-1] == "Green Text":
B2.config(fg ="red")
label.config(text ="Red Text", fg = "red")
else:
B2.config(fg ="green")
label.config(text ="Green Text", fg = "green")
B = Button(root, text = "Hello", fg="red", command=changeOne)
B2 = Button(root, text = "Click Me", fg="red", command=changeTwo)
label = Label(root, text ="Red Text", fg = "red")
B.place(x = 10,y = 10)
B2.place(x = 10, y = 40)
label.place(x = 10, y = 70)
root.mainloop()
问题在于if条件的这一部分:
if B.config('text')[-1] == "ITE 003":
,[-1]
。我真的不明白[-1]
如何帮助检索实际按钮的文本值,为什么它需要[-1]
?像数组一样吗?
答案 0 :(得分:1)
当您要从最右端开始访问列表的元素时,可以使用从-1开始的负索引值来引用它。请参阅下面提到的示例示例。
>>> li = [1,2,3,4]
>>> li[1]
2
>>> li[0]
1
>>> li[-1]
4
>>> li[-2]
3