Python Tkinter 脚本报错: AttributeError: '_tkinter.tkapp' object has no attribute 'success_var'

根据错误提示和代码分析,出现错误的原因是在start_fiddler函数中调用了simulate_shortcut函数,但是没有传入success_varfailure_var参数。simulate_shortcut函数中使用了这两个变量,所以会提示AttributeError,即找不到success_var属性。

为了解决这个问题,你需要在start_fiddler函数中传入success_varfailure_var参数。

start_fiddler函数的调用修改为:

simulate_shortcut(window.success_var, window.failure_var)

这样就能解决报错的问题。

代码示例

以下为完整的代码示例,已修复错误:

import time
import pygetwindow
import pyautogui
import schedule
import threading
import tkinter as tk
from tkinter import messagebox
import subprocess
import os


def is_fiddler_window_active():
    try:
        # 获取当前活动窗口
        active_window = pygetwindow.getActiveWindow()
        if active_window.title == 'Progress Telerik Fiddler Classic':
            return True
        else:
            return False
    except Exception as e:
        print('获取窗口信息失败:', str(e))
        return False


def open_fiddler(fiddler_path):
    try:
        if not os.path.exists(fiddler_path):
            print('Fiddler Classic 路径不存在')
            return False

        # 启动 Fiddler Classic
        subprocess.Popen(fiddler_path)

        # 判断 Fiddler Classic 是否启动成功
        for _ in range(10):
            if is_fiddler_window_active():
                print('成功激活 Fiddler Classic')
                return True
            time.sleep(1)

        print('启动 Fiddler Classic 失败')
        return False
    except Exception as e:
        print('启动 Fiddler Classic 失败:', str(e))
        return False


def simulate_shortcut(success_var, failure_var):
    global success_count, failure_count

    if is_fiddler_window_active():
        try:
            # 模拟按下 Ctrl + X 组合键
            pyautogui.hotkey('ctrl', 'x')
            time.sleep(0.5)  # 等待操作完成
            if not is_fiddler_window_active():
                print('模拟按下 Ctrl + X 后不在 Fiddler Classic 窗口中')
                failure_count += 1
                failure_var.set(f'执行失败{failure_count}次')
            else:
                print('成功模拟按下 Ctrl + X')
                success_count += 1
                success_var.set(f'执行成功{success_count}次')
        except Exception as e:
            print('模拟按键操作失败:', str(e))
            failure_count += 1
            failure_var.set(f'执行失败{failure_count}次')
    else:
        print('当前不在 Fiddler Classic 窗口中')
        failure_count += 1
        failure_var.set(f'执行失败{failure_count}次')


def run_script(seconds, countdown_label, success_var, failure_var, window):
    seconds -= 1

    if seconds < 0:
        seconds = int(window.seconds_var.get())
        open_fiddler(window.path_var.get())
        simulate_shortcut(success_var, failure_var)  # 传入 success_var 和 failure_var

    if not window.stop_flag:
        countdown_label.config(text=f'距离下次执行还有 {seconds} 秒')

    if not window.stop_flag:
        threading.Timer(1, run_script, args=(seconds, countdown_label, success_var, failure_var, window)).start()


def start_script(seconds, countdown_label, success_var, failure_var, window):
    global success_count, failure_count

    success_count = 0
    failure_count = 0

    if not seconds.isdigit():
        messagebox.showerror('错误', '输入无效,请重新输入整数类型的秒数!')
    elif window.stop_flag:
        window.stop_flag = False
        window.running_flag = True

        seconds = int(seconds)
        countdown_label.config(text=f'距离下次执行还有 {seconds} 秒')
        success_var.set('执行成功0次')
        failure_var.set('执行失败0次')

        threading.Timer(1, run_script, args=(seconds, countdown_label, success_var, failure_var, window)).start()
    elif window.running_flag:
        messagebox.showinfo('提示', '已经有倒计时在执行中,请稍后再试!')
    else:
        seconds = int(seconds)
        countdown_label.config(text=f'距离下次执行还有 {seconds} 秒')
        success_var.set('执行成功0次')
        failure_var.set('执行失败0次')

        window.stop_flag = False
        window.running_flag = True

        threading.Timer(1, run_script, args=(seconds, countdown_label, success_var, failure_var, window)).start()


def stop_script(countdown_label, window):
    window.seconds_var.set('10')

    countdown_label.config(text='停止运行')  # 更新文本内容
    window.seconds_entry.delete(0, tk.END)  # 清除文本框中的内容
    window.stop_flag = True
    window.running_flag = False


def start_fiddler(window, fiddler_path):
    if window.running_flag:
        messagebox.showinfo('提示', '已经有 Fiddler Classic 启动中,请稍后再试!')
        return

    if not open_fiddler(fiddler_path):
        messagebox.showerror('错误', '无法启动 Fiddler Classic,请检查路径是否正确!')
        return

    # 传入 success_var 和 failure_var 参数
    simulate_shortcut(window.success_var, window.failure_var) 

    for _ in range(10):
        if is_fiddler_window_active():
            break
        time.sleep(1)

    window.running_flag = True


def stop_fiddler(window):
    window.running_flag = False


if __name__ == '__main__':
    window = tk.Tk()
    window.title('Fiddler Classic 定时执行脚本程序')

    label = tk.Label(window, text='欢迎使用 Fiddler Classic 定时执行脚本程序!')
    label.pack(pady=10)

    window.seconds_var = tk.StringVar(value='10')

    seconds_label = tk.Label(window, text='请输入定时执行的时间间隔(秒):')
    seconds_label.pack()

    window.seconds_entry = tk.Entry(window, textvariable=window.seconds_var)
    window.seconds_entry.pack(pady=5)

    path_label = tk.Label(window, text='请输入 Fiddler Classic 路径:')
    path_label.pack()

    window.path_var = tk.StringVar()
    path_entry = tk.Entry(window, textvariable=window.path_var)
    path_entry.pack(pady=5)

    countdown_label = tk.Label(window, text='')
    countdown_label.pack(pady=5)

    success_var = tk.StringVar(value='执行成功0次')
    success_label = tk.Label(window, textvariable=success_var)
    success_label.pack(pady=5)

    failure_var = tk.StringVar(value='执行失败0次')
    failure_label = tk.Label(window, textvariable=failure_var)
    failure_label.pack(pady=5)

    start_button = tk.Button(
        window,
        text='开始执行',
        command=lambda: start_script(
            window.seconds_var.get(),
            countdown_label,
            success_var,
            failure_var,
            window
        )
    )
    start_button.pack(pady=10)

    stop_button = tk.Button(
        window,
        text='停止运行',
        command=lambda: stop_script(countdown_label, window)
    )
    stop_button.pack(pady=10)

    fiddler_start_button = tk.Button(
        window,
        text='启动 Fiddler Classic',
        command=lambda: start_fiddler(window, window.path_var.get())
    )
    fiddler_start_button.pack(pady=10)

    fiddler_stop_button = tk.Button(
        window,
        text='停止 Fiddler Classic',
        command=lambda: stop_fiddler(window)
    )
    fiddler_stop_button.pack(pady=10)

    window.stop_flag = False
    window.running_flag = False

    window.mainloop()

总结

通过添加success_varfailure_var参数到start_fiddler函数的调用中,就能解决AttributeError错误。

希望本教程能够帮助您解决问题!

Python Tkinter 脚本报错: AttributeError: '_tkinter.tkapp' object has no attribute 'success_var'

原文地址: https://www.cveoy.top/t/topic/qg4c 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录