Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter: Getting Canvas Attribute and Options Values

I imagine this is a fairly basic Tkinter question - but I am a noob and I haven't seen this answer after some searching.

I would like to be able to check what the attribute of my canvas is in Tkinter. So,

canvas = tk.Canvas(root, 200,200, bg="blue") 
canvas2 = tk.Canvas(root, 200,200, bg="red")
canvases = [canvas, canvas2]

What I am looking for is something to check what the attribute is of the canvas. For example -

for canvas in canvases:
   if canvas.get_color() == "red": # IS THERE SOMETHING LIKE get_color... or get_attr(bg)? 
        print("HECK YA")
   else:
        print("I'm feeling blue")

Thanks for the help!

like image 881
Hunter Avatar asked Mar 14 '26 09:03

Hunter


1 Answers

you can call canvas.config('attribute') to obtain the value of a given attribute. For instance canvas.config('bg') returns the value of the background.

Calling canvas.config() without arguments will return a dictionary of the current configuration

Universal Widget methods that relate to configuration of options:

The methods are defined on all widgets. In the descriptions, w can be any widget of any type.

w.cget(option): Returns the current value of option as a string. You can also get the value of an option for widget w as w[option].

w.config(option=value, ...) Same as .configure().

w.configure(option=value, ...) Set the values of one or more options. For the options whose names are Python reserved words (class, from, in), use a trailing underbar: 'class_', 'from_', 'in_'.

You can also set the value of an option for widget w with the statement w[option] = value

If you call the .config() method on a widget with no arguments, you'll get a dictionary of all the widget's current options. The keys are the option names (including aliases like bd for borderwidth). The value for each key is:

for most entries, a five-tuple: (option name, option database key, option database class, default value, current value); or,

for alias names (like 'fg'), a two-tuple: (alias name, equivalent standard name).

like image 90
Reblochon Masque Avatar answered Mar 16 '26 22:03

Reblochon Masque