My code contains two entry widgets, which are supposed to hold the height and width of an image. When the height or the width is adjusted by the user entering a number into one of the two widgets, the value of the other is supposed to be adjusted according to the entered value and a fixed aspect ratio.
My first approach was to bind the update functions to a key-press-event, but I encountered the error that leads to the bound function being executed before the textvariable is changed. The issue is described here: Tkinter, update Entry widget before calling <Key> binding. The proposed solution is to use variable tracing instead of key-press-event binding. However, since in my case the change of one variable executes a function which changes the other variable, I would have expected the functions to execute one another in an infinite loop. This doesn't happen, but the desired outcome is definitely not produced.
import tkinter as tk
import tkinter.ttk as ttk
class App:
def __init__(self, master, aspect_ratio):
self.master = master
self.aspect_ratio = aspect_ratio
self.shape_x = tk.DoubleVar()
self.shape_y = tk.DoubleVar()
self.shape_x.trace('w', self.update_y)
self.shape_y.trace('w', self.update_x)
# Entry for x dimension
self.entry_x = ttk.Entry(self.master, textvariable=self.shape_x, width=5)
self.entry_x.pack(side='left', fill='x', expand='yes')
# Label for multiplication sign
self.entry_label = tk.Label(self.master, text='x', fg='gray')
self.entry_label.pack(side='left')
# Entry for y dimension
self.entry_y = ttk.Entry(self.master, textvariable=self.shape_y, width=5)
self.entry_y.pack(side='left', fill='x', expand='yes')
def update_x(self, *args):
self.shape_x.set(self.shape_y.get() * self.aspect_ratio)
def update_y(self, *args):
self.shape_y.set(self.shape_x.get() / self.aspect_ratio)
if __name__ == '__main__':
root = tk.Tk()
app = App(master=root, aspect_ratio=2)
root.mainloop()
What would be the right way to achieve what I am looking for?
Edit: replaced * in update_y with /