You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python编写Win11睡眠按钮时,循环中Int转Tuple报错求助

问题解决:Windows睡眠按钮倒计时报错处理

错误根源

代码中多处语句末尾多余的逗号,导致Sleep_Timer被赋值为单元素元组(比如(9,))而非整数。Python里末尾加逗号的表达式会被解析为元组,这就是后续执行Sleep_Timer > 0比较、-=运算时出现类型错误的核心原因。另外,GetSleep_Time,是无效的递归调用写法,完全多余。

修正后的代码

import os
from tkinter import *
import time

Sleep_Timer = 10
app = Tk()
app.geometry()
app.title("Purple Monkeys Sleep Button")
app.config(background="black")

icon = PhotoImage(file='logo.png')
icon2 = PhotoImage(file='logo2.png')
app.iconphoto(True, icon)

def sleep():
    os.system("rundll32.exe powrprof.dll,SetSuspendState 0,1,0")

def GetSleep_Time():
    global Sleep_Timer
    # 重置计时器为初始值,避免多次点击后计数混乱
    Sleep_Timer = 10
    while Sleep_Timer > 0:
        Sleep_Timer -= 1  # 直接用 -= 简化更新逻辑
        print(Sleep_Timer)
        time.sleep(1)
        print("notsleeping")
    # 倒计时结束后触发睡眠
    sleep()

button = Button(app,
                text='SLEEP',
                command=GetSleep_Time,
                font=("Comic Sans",42),
                fg="green",
                bg="black",
                image=icon2,
                compound='bottom',
                activeforeground="green",
                activebackground="black")
button.pack()

app.mainloop()

关键修正点

  • 移除所有语句末尾多余的逗号,包括赋值、print、sleep调用等行;
  • 简化Sleep_Timer更新逻辑,直接用Sleep_Timer -= 1(变量本身是整数,无需额外int转换);
  • 删除无效的GetSleep_Time,递归调用,while循环本身可完成倒计时;
  • 增加倒计时结束后自动调用睡眠功能的逻辑,让按钮功能闭环;
  • 在GetSleep_Time开头重置计时器为10,避免多次点击按钮后计数从剩余值开始。

内容的提问来源于stack exchange,提问作者Purple Monkey Dishwasher Softw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 04:32:48