Home > Mobile >  Tkinter control scale and entry field with each other
Tkinter control scale and entry field with each other

Time:03-29

I have a scale and an input field which both control the same variable to give the user choice of which one they'd like to use. I've coded it a bit like this:

def scale_has_moved(value):
    entry_field.delete(0, END)
    entry_field.insert(0, str(float(value)))

    # Other functions I want the code to do

def entry_field_has_been_written(*args):
    value = float( entry_field.get() )
    scale.set(value)

This works, when I move the scale the entry_field gets written in and vice versa, and the other functions I want the code to do all happen. The obvious problem is the functions call each other in a loop, so moving the scale calls scale_has_moved() which calls the additional functions within and writes in the entry field, then because the entry field has been written in entry_field_has_been_written() gets called which in turn calls scale_has_moved() again, it doesn't go in an endless loop but it does everything at least twice everytime which affects performance. Any clue how I'd fix this? Thank you

CodePudding user response:

If you use the same variable for both widgets, they will automatically stay in sync. You don't need your two functions at all. The following code illustrates the technique.

import tkinter as tk

root = tk.Tk()

var = tk.IntVar(value=0)
scale = tk.Scale(root, variable=var, orient="horizontal")
entry = tk.Entry(root, textvariable=var)

scale.pack(side="top", fill="x")
entry.pack(side="top", fill="x")

root.mainloop()
  • Related