将参数传递给线程。参数源自 tkinter GUI 中的输入

Passing arguments to threading. Arguments originate from input in tkinter GUI

我正在使用 GUI 为 运行 编写脚本。 我使用 threading 有两个输入字段和两个按钮,因此我可以使用按钮开始和停止循环而不会冻结。 输入对于循环中的某些操作是必需的,我将简化它们,因为它是一个很长的 if 语句。

我从来没有做过线程,在我尝试实现它之前,应用程序已经运行了。 主要问题是如何将来自 GUI 的输入传递给线程? 它一直给我 argument not defined 错误。

这是代码,非常感谢任何帮助:

global x
global y

def scriptOne(x, y):
      print(x)
      print(y)

      while True:
        if pyautogui.locateOnScreen('agree.png', confidence=0.85) != None:
             print("Here are x&y: ", x, y)
        else:
             time.sleep(2)
             print("Waiting")

threadx=  threading.Thread(target=scriptOne, args=(x, y))

root = tkinter.Tk()

canvas = tkinter.Canvas(root, height=(heightR*.2), width=(widthR*.2), bg="#26292c")
canvas.pack()
frame= tkinter.Frame(root, bg="#26292c")
frame.place(relx=.1, rely=.1, relwidth=.8, relheight=.8)

xEntry=tkinter.Entry(frame, bg='#c5c7c4')
xEntry.place(relx=.4, rely=.05, relwidth=.75, relheight=.15)

yEntry=tkinter.Entry(frame, bg='#c5c7c4')
yEntry.place(relx=.4, rely=.3, relwidth=.75, relheight=.15)

labelX = tkinter.Label(frame, text="Pick", padx=1, pady=1, fg="white", bg="#26292c")
labelX.place(relx=0, rely=.05, relwidth=.25, relheight=.15)

labelY = tkinter.Label(frame, text="Ban", padx=1, pady=1, fg="white", bg="#26292c")
labelY.place(relx=0, rely=.3, relwidth=.25, relheight=.15)

startScript=tkinter.Button(frame, text="Activate Script", padx=10, pady=5, fg="white", bg="#52595d", command= lambda: threadx.start(xEntry.get(),yEntry.get()))
startScript.place(relx=.05, rely=.8, relwidth=.4, relheight=.2)

endScript=tkinter.Button(frame, text="Quit Script", padx=10, pady=5, fg="white", bg="#52595d", command=exit)
endScript.place(relx=.55, rely=.8, relwidth=.4, relheight=.2)

root.mainloop()

最好创建另一个函数来创建 Thread 实例并启动它:

def start_thread():
    # make sure x and y are input correctly
    try:
        x = int(xEntry.get().strip())
        y = int(yEntry.get().strip())
    except ValueError:
        print('Invalid x or y value')
        return

    # disable the button which is associated with this function
    startScript.config(state='disabled')

    # create thread and start it
    threading.Thread(target=scriptOne, args=(x,y), daemon=True).start()

然后把上面的函数赋值给startScript按钮:

startScript = tkinter.Button(frame, text="Activate Script", padx=10, pady=5,
                             fg="white", bg="#52595d", command=start_thread)