I have a slider to change the volume on my PC when I change the scale. However, it doesn't set the volume at the moment and I don't know why. Can someone please help me?
My code:
from tkinter import *
import tkinter as tk
from pyautogui import *
import pyautogui
window=Tk()
window.geometry("400x200")
def set_volume(val):
set.volume(scale.get() / 100.0)
scale = Scale(window, from_=100, to=0, length=150, orient='vertical', command=set_volume)
scale.set(50)
scale.pack(padx=20, pady=20)
window.mainloop()
-
1Can you please edit your question and clarify: What do you mean by "doesn't work"? What happens when you use it, and what did you expect to happen instead?Robert– Robert2025年10月10日 15:17:03 +00:00Commented Oct 10, 2025 at 15:17
-
1did you run it in console/terminal to see error messages? If you get error then show it in question (not in comments) as text (not image)furas– furas2025年10月10日 23:00:30 +00:00Commented Oct 10, 2025 at 23:00
1 Answer 1
Looking at the documentation for pyautogui, I don't see any method called set, so set.volume is invalid. It does mention 'volumedown', 'volumemute', and 'volumeup' in the keyboard functions, which is probably what you actually want.
import tkinter as tk
import pyautogui
window = tk.Tk()
window.geometry("400x200")
def set_volume(val) -> None:
global last_scale_value # allow this function to modify last_scale_val
val = int(val) # convert val to an integer
if val < last_scale_value:
pyautogui.press('volumedown')
elif val > last_scale_value:
pyautogui.press('volumeup')
# store the latest value for comparison
last_scale_value = val
scale = tk.Scale(
window,
from_=100,
to=0,
length=150,
orient='vertical',
command=set_volume
)
scale.set(50)
scale.pack(padx=20, pady=20)
# create a variable to compare against so we know which way the volume is being adjusted
last_scale_value = int(scale.get())
window.mainloop()
One important thing to note: this is NOT directly setting your computer's volume to the current value of the scale (pyautogui can't do that as far as I can tell) - it's sending keypresses based on changes to the scale.
Your computer usually doesn't consider keyboard volume key presses as a range between 0-100, typically one keypress will change the volume by a fixed amount > 1%. Keep this in mind!
Pro Tip: you don't need both the "star import"* and the regular import statement. You can (and probably should) just do import tkinter as tk and import pyautogui.
*See here for info on why star imports are regarded as a bad idea
2 Comments
pyautogui, but there may be other libraries out there for this sort of thing. That said, if you're doing thing on Windows it does usually involve some low-level library calls and stuff.