Sameer Pusegaonkar
Sameer Pusegaonkar

Reputation: 143

Method which returns the color of a label in Tkinter

I am trying to program 'The Game of Life' using Tkinter. Since I want to check the status of the neighbouring nodes using colours, I would like to know if there is a method which returns the colour of a label.

Thanks!

def checkNeighbours(i,j):
    alive_nodes=0
    if(labels[i+1][j].getColor()=="black"): 
        alive_nodes+=1
    if(labels[i][j+1].getColor()=="black"): 
        alive_nodes+=1
    if(labels[i-1][j].getColor()=="black"): 
        alive_nodes+=1
    if(labels[i][j-1].getColor()=="black"): 
        alive_nodes+=1
    if(labels[i+1][j+1].getColor()=="black"):   
        alive_nodes+=1
    if(labels[i-1][j-1].getColor()=="black"):   
        alive_nodes+=1
    if(labels[i+1][j-1].getColor()=="black"):   
        alive_nodes+=1
    if(labels[i-1][j+1].getColor()=="black"):   
        alive_nodes+=1
    return alive_nodes

Upvotes: 1

Views: 2326

Answers (1)

Kevin
Kevin

Reputation: 76194

You can use cget to get the value of a widget's configuration options. Example:

from tkinter import Tk, Label
root = Tk()
label = Label(text="hello", bg="red")
print("This label's color is:", label.cget("bg"))

Result:

This label's color is: red

You can also index the widget with the option name, e.g. label["bg"].

Upvotes: 3

Related Questions