'How to let tkinter Scale slider remember last position?

How do I let the slider object of tkinter Scale to remember the last position that the volume was at. The gif below shows what I am trying to achieve.

enter image description here

However, the gif shown above was just that I have set the value of that bar manually in the if statement of def toggle_mute_unmute. Below is a runnable code:

import tkinter as tk
from tkinter import ttk
from pygame import mixer

root = tk.Tk()
root.geometry("400x250")

mixer.init()


class Volume:
    def __init__(self) -> None:
        self.is_mute = False

    def create_buttons(self):
        self.audio_mute_button = tk.Button(relief=tk.FLAT, text="Speaker Icon", bg="silver", highlightthickness=0, bd=0, command=self.toggle_mute_unmute)
        self.audio_mute_button.grid(row=0, column=0, pady=25)
        
        self.create_volume_slider()

    def set_volume(self, volume: str) -> None:
        self.sound_volume = float(volume)

        if self.sound_volume == 0.0:
            self.audio_mute_button.config(text="Speaker Icon (Muted)")
        elif 0.25 >= self.sound_volume <= 0.5:
            self.audio_mute_button.config(text="Speaker Icon (Low Volume)")
        elif 0.5 >= self.sound_volume <= 0.75:
            self.audio_mute_button.config(text="Speaker Icon (Mid Volume)")
        else:
            self.audio_mute_button.config(text="Speaker Icon (High Volume)")

        mixer.music.set_volume(self.sound_volume)

    def create_volume_slider(self):
        self.volume_bar = ttk.Scale(
            from_=0, to=1,
            orient=tk.HORIZONTAL,
            length=150,
            command=self.set_volume
            )

        # Set the initial volume bar to 0.5
        self.volume_bar.set(0.5)

        # Grid the volume bar
        self.volume_bar.grid(row=0, column=9, padx=15)

        return self.volume_bar

    def toggle_mute_unmute(self):
        if self.is_mute:
            mixer.music.set_volume(self.sound_volume)
            self.volume_bar.set(0.5) # manually setting it
            self.is_mute = False
        else:
            mixer.music.set_volume(0.0)
            self.volume_bar.set(0.0)
            self.audio_mute_button.config(text="Speaker Icon (Muted)")
            self.is_mute = True

vol = Volume()
audio_btn = vol.create_buttons()
root.mainloop()

I know where the problem is, it's not doing how I want it to be because when I press the button, the line self.volume_bar.set(0.0) will set the value of self.sound_volume to 0. I also tried storing the value of the slider to a new variable but it didn't work because it follows the value of self.sound_volume.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source