Home > Enterprise >  How to pass mouse position to progress bar widget in Tkinter?
How to pass mouse position to progress bar widget in Tkinter?

Time:04-09

I am having trouble with passing the position of the mouse to progress bar widget slider created in Tkinter. I have code by which user can manipulate the progress bar, but by using another widget placed below. I want to eliminate the second widget. I am not able to pass the position of the mouse to the ttk.Progressbar.

The slider currently:

screenshot

The issue is to get rid of the widget below and be able to manipulate the green bar by mouse alone.

Current code:

from tkinter import *
from tkinter import ttk

root = Tk()
label = Label(root, text ='Progress Bar', font = "50")
label.pack(pady=5)

#mouse position
def motion(event):
    x, y = event.x, event.y
    print('{}, {}'.format(x, y)) 

#Progress Bar
progbar = ttk.Progressbar(root, orient=HORIZONTAL, length=220, mode="determinate", max=50.0)
progbar.pack(pady=20)
progbar.start()
progbar.stop()
progbar.bind('<B1-Motion>', motion)
var = IntVar()
progbar.config(variable=var) 

#Scale
scale = ttk.Scale(root, orient=HORIZONTAL, length=220, variable=var, from_ = 0.0, to= 50.0)
scale.pack()

root.geometry("300x150")
root.mainloop()

CodePudding user response:

You can use the mouse position to get the percentage of the x coordinate relative to the widget width. You can then multiply that percentage times the max value to get the appropriate value.

It might look something like this:

def motion(event):
    width = progbar.winfo_width()
    max_value = int(progbar.cget("max"))
    percent = min(max(event.x/width, 0), max_value)
    value = int(percent * max_value)
    var.set(value)

CodePudding user response:

You can get the x property of the event passed to the motion function and divide it by the progress bar width to get the mouse position relative to the progress bar. Then, you can use the value to update the progress bar to that proportion. To make calculations easier, I have change the max property of the progress bar to 1.

from tkinter import *
from tkinter import ttk

root = Tk()
label = Label(root, text ='Progress Bar', font="50")
label.pack(pady=5)

var = IntVar()

def motion(event):
    proportion = event.x / event.widget.winfo_width()
    var.set(proportion)

#Progress Bar
progbar = ttk.Progressbar(root, orient=HORIZONTAL, length=220, mode="determinate", max=1)
progbar.pack(pady=20)
progbar.start()
progbar.stop()
progbar.bind('<B1-Motion>', motion)
progbar.config(variable=var)

root.geometry("300x100")
root.mainloop()
  • Related