Search code examples
pythonfunctiontkintersensorsnon-linear

Connect a python tkinter progressbar to non-linear absolut values via function


I am looking for a function that dynamically calculates the progresbar of a python tkinter GUI. The special thing about it is, that the values to be displayed with the percentage of the progressbar are non-linear.

  • 100% should be absolut value 50
  • 0% should be absolut value 2
  • So the full range of the progressbar should therefore represent 48 absolut values. The problem now is, that (i.e. the half absolute value 24) should not represent the percentage value 50% but, for example, a percentage value of 74.

I get the values from an external sensor, which reads out data in real time.

How can I define this in a function that calculates the percentage values for each absolut value?

Thanks in advance!


Solution

  • This method should do the trick.

    def calculate_progress(value):
        absolute_min = 2
        absolute_max = 50
        progress_min = 0
        progress_max = 100
        absolute_range = absolute_max - absolute_min
        progress_range = progress_max - progress_min
        if value <= 24:
            progress = 1.5625 * value + 3.125
        else:
            progress = 2.0833 * value - 22.0833
        progress_percentage = ((progress - absolute_min) * progress_range) / absolute_range
        return progress_percentage
    

    Here is an example implementation.

    import tkinter as tk
    from tkinter import ttk
    
    def calculate_progress(value):
        absolute_min = 2
        absolute_max = 50
        progress_min = 0
        progress_max = 100
        absolute_range = absolute_max - absolute_min
        progress_range = progress_max - progress_min
        if value <= 24:
            progress = 1.5625 * value + 3.125
        else:
            progress = 2.0833 * value - 22.0833
        progress_percentage = ((progress - absolute_min) * progress_range) / absolute_range
        return progress_percentage
    
    def update_progress():
        global sensor_reading
        sensor_reading+=1
        progress = calculate_progress(sensor_reading)
        progress_bar['value'] = progress
    
    sensor_reading = 0
    root = tk.Tk()
    root.title("Non-Linear Progress Bar Example")
    
    progress_bar = ttk.Progressbar(root, length=400, mode='determinate', maximum=100)
    progress_bar.pack(pady=20)
    b = tk.Button(root,text='update', command=update_progress)
    b.pack()
    root.mainloop()
    

    Hope it helps!