0

Here's the code I have confusion with

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

The problem is with this part of the if condition: if B.config('text')[-1] == "ITE 003":, the [-1]. I really don't understand how the [-1] helps retrieve the actual button's text value, why does it need the [-1]? Is it like an array thing?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Orenjie
  • 13
  • 2

1 Answers1

1

When you want to access the element of the list starting from the rightmost end, you can refer it using negative index values beginning from -1. Refer to sample examples mentioned below.

>>> li = [1,2,3,4]
>>> li[1]
2
>>> li[0]
1
>>> li[-1]
4
>>> li[-2]
3
taurus05
  • 2,491
  • 15
  • 28
  • Hey thanks for answering! But does that mean the B.config('text') is an array? And the value for 'text' is at the right most end of its array? And if I want to get the value of different config options I would always have to use [-1]? – Orenjie Sep 27 '19 at 03:51
  • @Orenjie `B` is an object of type Button. When the method `config` is called with the parameter 'text', it returns a list of values. Now, from those returned list values, you know that the value you require is present at the last index of the list. But, you don't want to waste time calculating the length of the list and then check for the last value. To make things easier, you use negative indexing. If you want the value of different config option, you'll have to use either the same , or different index value. – taurus05 Sep 27 '19 at 04:09
  • 1
    I fully understand now, thanks so much! – Orenjie Sep 27 '19 at 06:01
  • Happy learning @Orenjie! – taurus05 Sep 27 '19 at 06:53