0

I am trying to get the values from two sliders after their values have been set and then use those values to create a new variable which is their quotient. The code that I found uses a function that will print the values, but I need to get the values returned to the main body of the program so that I can create the new variable and it is not working. from tkinter import *

def show_values():
    altitude =w2.get()
    speed = w1.get
    print (w1.get(), w2.get())
    return altitude,speed       #return variables

master = Tk()
w1 = Scale(master, from_=0, to=42)     #slider 1
w1.pack()
w2 = Scale(master, from_=0, to=200, orient=HORIZONTAL)   #slider 2
w2.pack()
Button(master, text='Show', command=show_values).pack()  #call function
                                                             #to get slider
time = altitude/speed
mainloop()   
Cirrus
  • 31
  • 1
  • Why not just move the `time = ` line into `show_values` itself? In any case, any code that appears before `mainloop` in the code body will execute in a fraction of a second, before the user can possibly move any sliders around. (and any code appearing after mainloop will never execute, because mainloop loops forever). Any logic that depends on user input should be inside a callback function. – Kevin Feb 09 '15 at 19:30
  • I think the problem is that I do not understand mainloop(). I am a beginner who has read Zelle's book, so i am more familiar with def main(): How can I access the two variables outside the function. I am trying to get the users input from the sliders in the window to do math in main(). Could you provide an example? Thanks in advance – Cirrus Feb 10 '15 at 00:25

1 Answers1

0

I may get downvoted for this, but I suggest using global variables. Make them before the function, and then set the inside the function itself. Like so:

gl_time = 0

def show_values():
    altitude =w2.get()
    speed = w1.get()
    global gl_time
    gl_time = altitude/speed    #set global variables to local ones
Blue
  • 545
  • 3
  • 13
  • For as simple a program as this, there's no harm in using globals. For any app getting bigger and less easy to overview, I would recommend using classes. This makes passing around variables between functions a whole lot easier through `self`. For a great template of Tkinter programs using one or more classes see [this answer](http://stackoverflow.com/a/17470842/3714930). – fhdrsdg Feb 09 '15 at 22:11
  • Does the function require return gl_time? I tried that as well as assuming that the function had modified gl_time, but print(gl_time) results in 0 -the initial value- – Cirrus Feb 10 '15 at 00:11
  • No, because time is a global variable. You can just assign a label to display it, then call master.update() at the end of the show_values() function. – Blue Feb 10 '15 at 00:17