0

I'm trying to create a GUI to run an experiment using tkinter. I need to assign the value selected by the user on a Scale widget to a variable called 'amount'. However, scale.get() always assigns the value '0' to amount, regardless of where I am on the Scale.

Most answers about the Scale widget seem to suggest that scale.get() works perfectly for everyone else, so I am not sure what I'm doing wrong. I'm using Python 3 and I wrote the following code to test just the get method:

import tkinter as tk

root = tk.Tk()
root.title("Test")
slider = tk.Scale(orient='horizontal', label = 'Amount', length = 500, from_= 0, to = 1000, bg = 'white', fg = 'black', sliderlength = 20)

amount = slider.get()
slider.pack()
print (amount)
root.mainloop()

According to other answers, amount should be equal to whatever value I choose on slider. But the print command prints 0.

This is my code and the slider.

This is the output.

Copy comment: I tried the following:

def get_value(var): 
    amount = var.get() 
    return amount 

var = tk.DoubleVar() 
scale = tk.Scale( root, variable = var ) 
scale.pack(anchor=CENTER) 
print (get_value(var))
stovfl
  • 14,998
  • 7
  • 24
  • 51
protonpasta
  • 45
  • 1
  • 6
  • 1
    the `amount` you print is the initial value when you first created your `Scale` widget, which is 0. What you need is a function to retrieve the new value when executed. – Henry Yik Mar 30 '19 at 07:25
  • @HenryYik could you elaborate on how I can do that? I tried the following: `def get_value(var): amount = var.get() return amount var = tk.DoubleVar() scale = tk.Scale( root, variable = var ) scale.pack(anchor=CENTER) print (get_value(var))` – protonpasta Mar 30 '19 at 09:45
  • 1
    @aasthas: `Tkinter` uses the concept of **event-driven programming**, in which custom-written `callback` functions, receive the flow of control from the `.mainloop()` dispatcher. First you have to understand [Event-driven programming](https://stackoverflow.com/a/9343402/7414759) – stovfl Mar 30 '19 at 09:56

1 Answers1

0

You can link a command to your scale and get rid of the amount = slider.get() and the print(amount). This is the code:

import tkinter as tk

def get_value(v):
    print(v)

root = tk.Tk()
root.title("Test")
slider = tk.Scale(orient='horizontal', label = 'Amount', length = 500, from_= 0, to = 1000, bg = 'white', fg = 'black', sliderlength = 20, command=get_value)
slider.pack()

root.mainloop()
Walt
  • 7
  • 5