-1

How to get the values of spinbox from and to in a function?

sbDays=tk.Spinbox(frame,from_=0,to=366)
sbDays.place(relx=initialX,rely=yDistance)
sbDays.configure(validate='all',validatecommand=(windows.register(validate),'%P'))

def validate(userInput): 
    if userInput=="":
        return True

    try:
        val=int(float(userInput))
    except ValueError:
        return False
    return val>=0 and val<=366

Instead of return val>=0 and val<=366. I need this:

minVal=spinbox 'from' value of '0'
maxVal=spinbox 'to' value of '366'

return val>=minVal and val<=maxVal

In C#, something like this:

minVal=this.From()
maxVal=this.To()
Vincent
  • 145
  • 2
  • 11

2 Answers2

3

You can use the cget method to get attributes from a widget.
In this case, you need minVal = sbDays.cget("from") and maxVal = sbDays.cget("to")

Edit - For multiple spinboxes
To use this with multiple spinboxes, change the validatecommand to
validatecommand=(windows.register(validate),'%P', '%W')
and change validate(userInput) to validate(userInput, widget). Then replace sbDays in my answer with windows.nametowidget(widget) and it should work.
The %W in the validatecommand gives the name of the widget (from here), which is then used to get the widget with nametowidget (from here).

Henry
  • 3,472
  • 2
  • 12
  • 36
  • Is there a reason why `cget` is better than `config` or is it just a preference? I usually use `config` to set and get values from tkinter widgets. – TheLizzard Feb 22 '21 at 11:58
  • @TheLizzard I forgot to mention that I have several spinbox that is calling from the function. – Vincent Feb 22 '21 at 11:59
  • @TheLizzard From the looks of [this answer](https://stackoverflow.com/a/3222000), it seems like they're pretty much the same – Henry Feb 22 '21 at 12:01
  • @Vincent I've updated my answer to work with multiple spinboxes – Henry Feb 22 '21 at 12:13
  • It worked. I'm using C# for 8years now and today marks my 3rd day of using Python. It seems the syntax and calling the functions are way too different. – Vincent Feb 22 '21 at 12:28
  • Glad that helped. Tkinter does have some odd syntax sometimes. – Henry Feb 22 '21 at 13:43
  • 2
    @TheLizzard: `config` will return a list of values. `cget` returns exactly one value, making it more convenient if you're only interested in the currently configured value. – Bryan Oakley Feb 22 '21 at 14:50
0

You can also use the .config method like this: sbDays.config("from") and sbDays.config("to"). It returns something like ('from', 'from', 'From', 0, 0.0) or ('to', 'to', 'To', 0, 366.0). Note the last value is the one we need so using sbDays.config(...)[-1] should give the desired result.

TheLizzard
  • 7,248
  • 2
  • 11
  • 31