I am making a simple calculator using Python and tkinter and I wanted to save code by making global attributes.
I would like to set default attributes instead of:
myButton = Button(self, text = "A", width = 50, height = 50);
myButton.grid(row = 0, column = 0, width = 50, height = 50);
myButton = Button(self, text = "A", width = 50, height = 50);
myButton.grid(row = 0, column = 1);
myButton = Button(self, text = "A");
myButton.grid(row = 0, column = 2);
myButton = Button(self, text = "A");
myButton.grid(row = 0, column = 3);
I would like to make a default attribute for the Button
widget. Any way to make that happen?
The simplest option is probably to create a dictionary of the arguments you want to use as defaults (like the width
and height
I assume), and pass them in as **kwargs
to each Button
And (as @Sembei mentioned), if you need to retain references to each button, you have to use different names for each variable. I've changed them here as an example
# create a dictionary of the properties you want to share for each button
btn_props = {
'width': 50,
'height': 50,
# add other args here as needed
}
# pass 'btn_props' in as keyword arguments (a.k.a. 'kwargs')
myButton1 = Button(self, text = "A", **btn_props);
myButton1.grid(row = 0, column = 0);
myButton2 = Button(self, text = "A", **btn_props);
myButton2.grid(row = 0, column = 1);
myButton3 = Button(self, text = "A", **btn_props);
myButton3.grid(row = 0, column = 2);
myButton4 = Button(self, text = "A", **btn_props);
myButton4.grid(row = 0, column = 3);
Another option is to create your own button class that inherits from tk.Button
, but that's slightly more involved
User @TheLizzard has also raised another good point: buttons aren't sized in units of pixels. If you want to do that, the method outlined here is a good solution!