Reputation: 394
I made a scale in Tkinter using the code below:
demo = ttk.Labelframe(col2, text='Demo', padding=(15, 10))
demo.pack(side='top', fill='both', expand='yes', pady=(10, 0))
epoch = ttk.Frame(demo)
epoch.pack(fill='x', padx=(20, 0), pady=(5, 0))
ttk.Label(epoch, text='10 epoch').pack(side='left')
ttk.Label(epoch, text='1000 epoch').pack(side='right')
ttk.Scale(epoch, value=990, from_=10, to=1000).pack(side='left', fill='x', expand='yes', padx=(30, 0))
I want to have a label that displays the value of the scale at its current position in real time right below it. How should I achieve that?
Upvotes: 0
Views: 1110
Reputation: 3089
From my understanding of your question, you want to place the label right below the handle of your Slider/Scale widget. This can be easily achieved using the place
on a Label
. To get the x, y
coordinates of the handle use the scale.coords
.
Minimal example:
from tkinter import ttk
import tkinter as tk
def update_lbl(*args):
x, _ = scale.coords() # gets handle x position
y, h = scale.winfo_y(), scale.winfo_height() # get the widgets y position and height
scale_lbl.place(x=x, y=h+y)
root = tk.Tk()
val = tk.IntVar(root)
val.set(0)
scale_lbl = tk.Label(root, textvariable=val)
scale = ttk.Scale(root, variable=val, from_=10, to=1000)
scale.pack(side='left', fill='x', expand='yes', padx=(30, 0))
scale.bind('<Configure>', lambda ev: scale.after(1, update_lbl))
val.trace('w', update_lbl)
root.mainloop()
output:
Upvotes: 1
Reputation:
You can create an IntVar()
scale_val=IntVar()
ttk.Scale(epoch, value=990,variable=scale_val, from_=10, to=1000).pack(side='left', fill='x', expand='yes', padx=(30, 0))
lbl_val=ttk.Label(epoch)
lbl_val.pack(side='bottom') #=== Set it according to your will
Then you can trace the variable:
def trace_method(*args):
x=scale_val.get()
lbl_val.config(text=f'{x} %')
scale_val.trace('w',trace_method)
Upvotes: 2