If you're writing some Tkinter software and you're sizing something in inches or centimeters and tkinter only gives you feedback in pixel distances then you may need a way to get back to your prefered units of measure. I recently found myself in this situation. There's nothing fancy about the set of functions here, it's more about the little known winfo_fpixels() function. Once you know about this everything else is a piece of cake. These functions are simple, but convenient.
Python, 112 lines
Clearly I didn't need to define a class since all the methods are static. It's just a design preference. Before any method in this class is called, it's necessary to call setup() and pass it a widget. Any ol' widget will do. This only needs to be done one time. setup() will use the widget to determine the conversion constants. I prefer to call setup immediately after I create my root widget so I called my parameter 'root'.
Each of the six conversion functions requires its argument as a python float or integer value. Python floats are always returned.
tkDistance is a simple Pythagorean Theorem implementation. All four arguments must be in python float or integer values, all in the same units (pixels, inches, cm or mm). The result is a python float in the same units as was entered. I've found common idiom to their usage to be:
root = Tk() tkMath.setup( root )
... def myEventCB( event ): distance = tkMatho.tkDistance( initialx, initialy, event.x, event.y )
distanceInInches = tkMath.pixelsToInches( distance )
vector requires all arguments as python floats and/or ints. direction should be provided in radians with zero at 3 o'clock and values incrementing clock-wise: So straight down is 1/2 * PI, to the left if PI and straight up is 3/2 * PI. With x1,y1 being the starting coordinate for the vector, the result is a tuple x,y of the ending coordinates.
I've found tk measurements to be highly accurate on any display I've experimented with. That is if I do something such as draw a 3 inch line on a canvas widget and measure it with a ruler up against the screen, I get just about three inches.