首页 > 解决方案 > 按住开始按钮的自动答题器问题

问题描述

我正在使用pyautogui自动点击器程序编写,程序由三个按钮(开始、停止、退出)和一个组合框组成。我的问题是当我按下开始按钮时,按钮被按住并且我无法按下另一个按钮。我用while循环编写了点击函数。我想在程序运行时按其他按钮。

from tkinter import *
from tkinter import ttk
from threading import Thread
import pyautogui

def durdur():
    global veri,baslat
    def thread():
        baslat.config(relief="sunken",state=DISABLED,text="Stop")
        run = Thread(target=tikla,args=(baslat))
        run.start()

    veri = ttk.Combobox(p, width=30)
    veri["values"] = ("Left Click", "Right Click")
    veri.place(x=13, y=10)

    baslat = Button(p, text="Start",  width=8, height=2,command=tikla)
    baslat.place(x=10, y=40)

    durdur = Button(p, text="Stop", width=8, height=2, command=thread)
    durdur.place(x=80, y=40)

    cikis = Button(p, text="Exit", width=8, height=2, command=lambda: 
 p.destroy())
    cikis.place(x=150, y=40)

#click function
def tikla():
    t=veri.get()
    if t=="Left Click":
        while True:
                pyautogui.click(clicks=1,interval=0.5,button="left")
                baslat.config(relief="raised",state=NORMAL,text="Start")
    elif t=="Right Click":
        while True:
            pyautogui.click(clicks=1,interval=0.06,button="right")
            baslat.config(relief="raised", state=NORMAL, text="Start")
    else:
        pass

p=Tk()
durdur()
p.title("Auto Clicker")
p.geometry("250x100")


if __name__=="__main__":
    p.mainloop()

标签: python-3.x

解决方案


在处理事件时,您的 GUI 将被阻止并且无法自行更新(直到事件完成)。相反,您可以使用 tkinterafter方法来安排您的点击。

在按钮单击时,您可能希望输入一个执行一次“自动单击”的函数,然后安排自己在设定的时间后再次运行。after下面是一个用于在不阻止 GUI 的情况下执行操作的示例。

import tkinter as tk

class AfterExample:
    def __init__(self):
        self.root = tk.Tk()
        self.b1 = tk.Button(master = self.root, text = "Turn on", command = self.b1_cmd)
        self.b2 = tk.Button(master = self.root, text = "Turn off", command = self.b2_cmd)
        self.b1.pack()
        self.b2.pack()
        self._job = None # Represents the scheduled event

    def b1_cmd(self):
        if self._job is None: # Only start if it isn't already running
            self._job = self.root.after(0, self.clicker)
        return

    def clicker(self):
        print("<CLICK>")
        self._job = self.root.after(100, self.clicker)
        return    

    def b2_cmd(self):
        print("Stopping!")
        if self._job is not None: 
            self.root.after_cancel(self._job)
            self._job = None
        return

    def start(self):
        self.root.mainloop()

a = AfterExample()
a.start()

推荐阅读