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

Tkinter自动关机脚本打包成可执行文件后运行报错:'_tkinter.tkapp' object has no attribute 'main'

Tkinter自动关机脚本打包成可执行文件后运行报错:'_tkinter.tkapp' object has no attribute 'main'

我仔细看了你的脚本和报错信息,首先能发现一个非常明显的拼写错误,这也是导致你运行(包括打包后)报错的核心原因之一,另外还有几个潜在问题也会影响脚本的稳定性和打包效果,下面一步步给你梳理:

1. 致命拼写错误:主事件循环调用错误

你的脚本最后一行写的是:

root.main

这完全是写错了!Tkinter启动主界面事件循环的正确语法是root.mainloop()——少了loop()方法调用,导致程序根本无法启动GUI界面,打包成exe后自然会抛出'_tkinter.tkapp' object has no attribute 'main'的错误。

2. 输入合法性未校验,容易崩溃

当前脚本直接把输入框的内容转成整数,如果用户输入了非数字内容(比如字母、空值),或者输入了超出合理范围的数值(比如小时输入25、分钟输入60),脚本会直接抛出ValueError崩溃。需要添加异常处理来避免这种情况。

3. 长时间sleep阻塞GUI界面

脚本里用time.sleep(time_remaining)来等待关机时间,这会导致整个Tkinter界面完全卡死,用户无法进行任何操作(比如想取消关机都做不到)。更合理的做法是用Tkinter自带的after()方法来定时触发关机操作,这样界面还能保持响应。

4. 打包成可执行文件的注意事项

如果用PyInstaller打包,需要注意:

  • 如果你不想显示控制台窗口,打包时要加--windowed(或-w)参数,但调试阶段建议去掉这个参数,方便查看报错信息;
  • 少数情况下PyInstaller可能无法自动识别Tkinter依赖,打包时可以加上--hidden-import tkinter参数确保依赖被包含。

修正后的完整脚本

import tkinter as tk
import time
import os
from tkinter import messagebox

# Cria a janela principal
root = tk.Tk()
root.title("Desligamento Automático")

# Cria os campos de entrada para o dia, hora e minuto
day_label = tk.Label(root, text="Dia:")
day_label.grid(row=0, column=0, padx=5, pady=5)
day_entry = tk.Entry(root, width=10)
day_entry.grid(row=0, column=1, padx=5, pady=5)

hour_label = tk.Label(root, text="Hora:")
hour_label.grid(row=1, column=0, padx=5, pady=5)
hour_entry = tk.Entry(root, width=10)
hour_entry.grid(row=1, column=1, padx=5, pady=5)

minute_label = tk.Label(root, text="Minuto:")
minute_label.grid(row=2, column=0, padx=5, pady=5)
minute_entry = tk.Entry(root, width=10)
minute_entry.grid(row=2, column=1, padx=5, pady=5)

shutdown_id = None  # 用来存储after的ID,方便取消定时

def cancel_shutdown():
    global shutdown_id
    if shutdown_id:
        root.after_cancel(shutdown_id)
        shutdown_id = None
        messagebox.showinfo("Sucesso", "Desligamento cancelado!")

def shutdown():
    global shutdown_id
    try:
        # Obtém o dia, hora e minuto do desligamento
        day = int(day_entry.get())
        hour = int(hour_entry.get())
        minute = int(minute_entry.get())

        # Valida os valores
        if not (1 <= day <= 31):
            raise ValueError("Dia deve estar entre 1 e 31")
        if not (0 <= hour <= 23):
            raise ValueError("Hora deve estar entre 0 e 23")
        if not (0 <= minute <= 59):
            raise ValueError("Minuto deve estar entre 0 e 59")

        # Obtém o horário atual
        current_time = time.localtime()
        # Define o horário de desligamento
        shutdown_time = (current_time.tm_year, current_time.tm_mon, day, hour, minute, 0,
                        current_time.tm_wday, current_time.tm_yday, current_time.tm_isdst)

        # Calcula o tempo restante até o desligamento(毫秒)
        time_remaining = int((time.mktime(shutdown_time) - time.mktime(current_time)) * 1000)

        if time_remaining <= 0:
            messagebox.showerror("Erro", "Horário de desligamento deve ser no futuro!")
            return

        # 使用after代替sleep,避免阻塞GUI
        shutdown_id = root.after(time_remaining, execute_shutdown)
        messagebox.showinfo("Sucesso", f"Desligamento agendado para {day}/{current_time.tm_mon} às {hour}:{minute}")

    except ValueError as e:
        messagebox.showerror("Erro de entrada", str(e))

def execute_shutdown():
    # Desliga o computador
    os.system("shutdown /s /t 0")

# Cria os botões
shutdown_button = tk.Button(root, text="Agendar Desligamento", command=shutdown)
shutdown_button.grid(row=3, column=0, padx=5, pady=10)

cancel_button = tk.Button(root, text="Cancelar Desligamento", command=cancel_shutdown)
cancel_button.grid(row=3, column=1, padx=5, pady=10)

# Executa a janela(修正后的正确写法)
root.mainloop()

打包命令示例(用PyInstaller)

如果你的脚本名叫shutdown_app.py,可以用以下命令打包:

# 调试版本(显示控制台)
pyinstaller shutdown_app.py

# 正式版本(隐藏控制台)
pyinstaller --windowed shutdown_app.py

备注:内容来源于stack exchange,提问作者Mocha

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.23 06:59:54