我是python编码的新手,我一直在做一个项目,可以根据选择的颜色点击图像。我一直在使用一个程序,当我点击开始按钮时,它会循环搜索50次。然而,我一直在尝试实现一个停止按钮,但问题是我的代码在循环运行时冻结。有什么想法吗?在
我听说过尝试线程,但它似乎非常复杂,我无法正确地遵循与我的代码相关的任何教程。顺便说一下,搜索到的图像一直在测试我使用的存储在程序文件中的图像。在
from imagesearch import *
import pyautogui
import tkinter as tk
from tkinter import *
from tkinter.ttk import *
import time
import threading
# ---Defined Programs---
def run():
global enterColor
enterColor = str(enterColorField.get())
program(enterColor)
def program(color):
whitePos = imagesearch_numLoop(str(color) + ".PNG", 0, 50)
pyautogui.moveTo(whitePos[0] + 20, whitePos[1] + 10)
pyautogui.click()
def stop():
print("Placeholder")
# ---Main Runner---
window = tk.Tk()
window.geometry("250x250")
window.configure(background="#181b54")
app = tk.Frame(window)
app.grid()
enterColorLabel = tk.Label(window, text="Enter Color:", bg="#181b54", fg="white")
enterColorLabel.place(x=10, y=50)
enterColorField = Combobox(window)
enterColorField['values'] = ("Black", "White")
enterColorField.current("0") # set the selected item
enterColorField.place(x=10, y=70)
submitButton = tk.Button(window, text="Start", bg="#66ff00", command=run)
submitButton.place(x=10, y=130)
stopButton = tk.Button(window, text="Stop", bg="red", command=stop)
stopButton.place(x=50, y=130)
window.mainloop()
#---New Python Script---
import cv2
import numpy as np
import pyautogui
import random
import time
def imagesearch_numLoop(image, timesample, maxSamples, precision=0.8):
pos = imagesearch(image, precision)
count = 0
while pos[0] == -1:
print(image+" not found, waiting")
count = count + 1
if count>maxSamples:
break
pos = imagesearch(image, precision)
return pos
无论何时单击start,整个代码都会冻结。我甚至不能出去。在
这里有一个很有希望的简单的多处理方法,将为您工作。我们将有三个主要功能。第一个是一个示例循环,您可以将处理放在其中。我在函数中包含了参数,以向您展示在使用多处理时可以传递arg和kwargs。在
接下来是一个函数,我们将用来对多处理进程进行排队。在
^{pr2}$你可能会对你的整个执行过程感兴趣。例如,有时需要在运行命令时禁用某些按钮。在
把这些都放在一个片段里:
结果是,当您单击“Using MP”按钮时,命令按钮将被禁用,并且该过程将在不冻结用户界面的情况下启动。单击“notmp”按钮将启动类似“normal”的函数,并将冻结您在自己的代码中注意到的UI。在
一个简单的答案是不能在GUI设计中使用while循环。在
但是您可以使用方法
.after(delay, callback=None)
。在下面是一个例子:
相关问题 更多 >
编程相关推荐