如何让 tkinter Scale 滑块记住最后一个位置?

How to let tkinter Scale slider remember last position?

如何让 tkinter Scale 的滑块对象记住音量的最后位置。下面的 gif 显示了我正在努力实现的目标。

然而,上面显示的gif只是我在def toggle_mute_unmute的if语句中手动设置了那个bar的值。下面是一个可运行的代码:

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()

我知道问题出在哪里,它没有按我想要的方式运行,因为当我按下按钮时,行 self.volume_bar.set(0.0) 会将 self.sound_volume 的值设置为 0。我也尝试将滑块的值存储到一个新变量,但没有成功,因为它遵循 self.sound_volume.

的值

在静音之前记住滑块位置的一种方法是简单地将其存储在变量中,例如self.prev_sound_volume。下面是如何修改toggle_mute_unmute():

def toggle_mute_unmute(self):
    if self.is_mute:
        mixer.music.set_volume(self.prev_sound_volume)
        self.volume_bar.set(self.prev_sound_volume) # go back to previous volume
        self.is_mute = False
    else:
        self.prev_sound_volume = self.sound_volume  # store value of volume before muting
        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