当我调用 pyautogui 命令时,tkinter 不断崩溃

tkinter keeps crashing when I call pyautogui commmand

我最近一直在尝试制作使用 tkinter 和 pyautogui 的简单程序 pyautogui 一个人没有 tkinter 就可以正常工作,但是当我决定开始使用 GUI 将它们制作成 tkinter 时,它一直在崩溃我认为发生这种情况的原因是即使我输入了 root.update() 按钮也会一直被按下似乎不再被按下,但它被按下并执行命令。

没有 tkinter 的代码:

import pyautogui,time
time.sleep(5)
f = open("mytext.txt", 'r')
time.sleep(5)
for word in f:
    pyautogui.typewrite(word)

使用 tkinter:

import tkinter as tk
import pyautogui,time
root = tk.Tk()
def stop_writing():
    global btn 
    btn.config(command = None)
def write():
    root.update()

    time.sleep(5)
    f = open("mytext.txt", 'r')

    for word in f:
        pyautogui.typewrite(word)
    pyautogui.mainloop()

btn = tk.Button(root, text = "start writing" , command = write)
btn.pack()     
btn_disable = tk.Button(root, text = "stop writing" ,command = stop_writing)
btn_disable.pack()
root.mainloop()

有什么方法可以防止它崩溃吗?

阻止 Tkinter 崩溃的唯一方法是不在主线程中使用 time.sleep

我建议您为 pyautogui.typewrite 创建一个单独的线程。另外,请注意你不应该从不同的线程更新 Tkinter 组件,因为 Tkinter 不是线程安全的。

我将展示如何使用多线程来做到这一点。

import tkinter as tk
import pyautogui,time, threading


def stop_writing():
    global _stop, thread
    if thread:
        _stop = True
        thread.join()

def write():
    
    time.sleep(2)
    with open(r"file.txt", 'r') as f:
        content = f.read()

    for word in content:
        if _stop:
            return
        pyautogui.typewrite(word)


def start():
    global thread, _stop

    if thread and thread.is_alive():
        stop_writing()

    thread = None
    thread = threading.Thread(target=write)
    thread.daemon = True
    _stop = False
    thread.start()
    

root = tk.Tk()
root.attributes('-topmost', True)
root.protocol("WM_DELETE_WINDOW", lambda: [stop_writing(), root.destroy()])
_stop = False
thread = None

btn = tk.Button(root, text = "start writing" , command = start)
btn.pack()     
btn_disable = tk.Button(root, text = "stop writing" ,command = stop_writing)
btn_disable.pack()

text = tk.Text(root)
text.pack()

root.mainloop()

您也可以使用 root.after 并在几秒钟后调用您的写入函数。

一些小错误:

  1. 打开文件时应始终将其关闭。
  2. 我查了pyautogui的文档,没找到mainloop之类的方法