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

Python Tkinter GUI实现磁盘清理按钮点击无响应问题求解

Tkinter按钮绑定功能修复方案

核心问题原因

你代码的故障根源是给Tkinter按钮的command参数传递值时添加了函数调用括号,导致程序初始化阶段就直接执行了磁盘清理逻辑,而非将函数本身绑定为点击触发的回调,所以会出现功能先执行、GUI后显示,点击按钮无响应的问题。

需修改的细节点

  • 按钮command参数改为传递函数引用,去掉调用括号
  • 移除btn1函数内多余的if __name__ == "__main__"判断,该判断仅适用于模块入口场景,内部函数中使用无意义
  • 修正系统命令拼写错误:Cleanmgr.exe后需要加空格,原命令参数格式错误会导致清理功能无法正常触发
  • 提前确认你已经配置过Cleanmgr.exe /sageset:1设置过默认清理项,否则sagerun:1参数不会生效

修复后完整代码

import shutil
import os
import tkinter as tk
from tkinter import ttk

# 保留你原有的Page父类定义即可,此处假设你已正确实现父类逻辑
class Page3(Page):
   def __init__(self, *args, **kwargs):
      Page.__init__(self, *args, **kwargs, bg='white')
      label = ttk.Label(self, text="This is page 3")
      label.grid(row=2, column=1)
      
      def mytools():
           total, used, free = shutil.disk_usage("/")
           print("Total:%d GB" % (total // (2**30)))
           print("Used:%d GB" % (used // (2**30)))
           print("Free:%d GB" % (free // (2**30)))

           if free <= total/2:
               # 修正清理命令格式
               clean = os.popen('Cleanmgr.exe /sagerun:1').read()
               print(clean)
      
      def btn1():
           mytools()
      
      # 核心修改:command参数传递函数引用,不加调用括号
      button1 = ttk.Button(self, text="Clean Up", command=btn1)
      button1.grid(row=3, column=2)

内容的提问来源于stack exchange,提问作者Jun Jie Ong

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 23:27:01