Hello! I've been messing with tkinter and now have tried to make a MPG calculator using sliders.

My problem is that no matter how I move the sliders it does not update the mpg, I'm not sure what to tell the label to do for it to update.

I know the calculations themselves work because I made it print to the console as a test and it updated there.

import tkinter as tk


root = tk.Tk()
root.title('MPG calculator')

root.geometry("620x200+300+300")


scale = tk.Scale(root, label="Select a distance traveled.",
    from_=1, to=1500, tickinterval=0, resolution=1, length=600,
    showvalue='yes', orient='horizontal')

scale.set(500)

scale2 = tk.Scale(root, label="Select how large your fuel tank is.",
    from_=1, to=80, tickinterval=0, resolution=1, length=600,
    showvalue='yes', orient='horizontal')

scale.set(12)

dist = scale.get()
tank = scale2.get()
f = dist / tank
result = 'You get %s miles per gallon.' % (f)

label = tk.Label(root, text= result, bg='green')


scale.grid(row=2, columnspan=2)
scale2.grid(row=1, columnspan=2)
label.grid(row=4, columnspan=4, pady=5)

root.mainloop()

Thanks!

edit:
The attached file shows my problem. It shows 12 mpg no matter what.

You need event handling.
Put this function at top after import like this.

import tkinter as tk

def on_move(value=0):
    f = scale.get()    
    label['text'] = f

Now you see that your down slider is working.
So now just figure out the calulate stuff,and you have a nice program.

Forget i made change to this 2 lines to.

scale = tk.Scale(root, label="Select a distance traveled.",
    from_=1, to=1500, tickinterval=0, resolution=1, length=600,
    showvalue='yes', orient='horizontal',command=on_move)

label = tk.Label(root, text='---', bg='green')

Thanks it's all sorted out now, a nifty little program :).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.