【问题标题】:pyautogui works from terminal but not tkinter buttonpyautogui 适用于终端但不适用于 tkinter 按钮
【发布时间】:2016-05-23 01:47:33
【问题描述】:

晚上好, 我正在尝试学习一些 Python 编码,所以我编写了一个简短的脚本,它在屏幕上搜索一个按钮,然后单击该按钮指定的次数。我将“RunScript”下的代码也保存为它自己的文件。当我从终端运行该脚本时,它工作正常,但是当我尝试通过双击图标或使用下面的代码从 tkinter 框上的按钮执行它时,它会询问我一些循环,然后什么也不做。我正在使用 Lubuntu 虚拟机。 请你能告诉我我错过了什么吗? 谢谢

#!/usr/bin/python3

from tkinter import *
import pyautogui
import easygui
PauseStatus = False

def RunScript():
    LoopCount = easygui.enterbox('How Many Loops?')
    for i in range (int(LoopCount)):
        if PauseStatus:
            easygui.msgbox(str(i) + ' loops completed\n' + str(int(LoopCount)-i) + 'loops remaining')
            PauseStatus = False
        while True:
            ButtonPos = pyautogui.locateOnScreen('MyButton.png')
            if ButtonPos is not None:
                break
        pyautogui.click(ButtonPos[0],ButtonPos[1],duration=0.25)
    while True:
        ButtonPos = pyautogui.locateOnScreen('MyButton.png')
        if ButtonPos is not None:
            break
    easygui.msgbox(str(i+1) + ' loops completed')

root = Tk()
ControlPanel = Frame(root)
ControlPanel.pack()

startbutton = Button(ControlPanel, text="Start",command = RunScript)
startbutton.pack(side = LEFT)

stopbutton=Button(ControlPanel,text="Stop")
stopbutton.pack(side = LEFT)

root.mainloop()

【问题讨论】:

  • 在终端运行 tkinter 脚本 - 也许你会收到错误消息。
  • 顺便说一句:locateOnScreen 总是返回相同的位置(第一个找到的按钮),所以你不需要使用while 循环。
  • 谢谢。我从终端运行并收到您在下面提到的错误消息。我将 PauseStatus 移到 def 部分内部,现在它可以工作了。
  • 按钮在被按下后变灰,然后在准备好再次按下时变灰。 while 循环的目的是确保代码不会尝试按下灰色按钮,尽管我确实打算将其更改为单独存储按钮位置,然后仅在屏幕的该区域搜索图像每个循环使其更快。我也读过要让 Pause 工作,我需要将 while 循环更改为 after,但我仍在努力使其工作。再次感谢

标签: python ubuntu tkinter pyautogui


【解决方案1】:

你有类似这样的错误信息

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1539, in __call__
    return self.func(*args)
  File "<pyshell#3>", line 11, in RunScript
    if PauseStatus:
UnboundLocalError: local variable 'PauseStatus' referenced before assignment

你必须在函数RunScript中使用global

def RunScript():
    global PauseStatus

或者你必须将函数内部的变量声明为局部变量

def RunScript():
    PauseStatus = False

【讨论】:

  • 我在终端收到此错误消息并应用了您的修复。现在,当我单击 tkinter 框上的按钮时,代码可以工作。谢谢
猜你喜欢
  • 2015-01-21
  • 1970-01-01
  • 1970-01-01
  • 2020-08-03
  • 2020-01-13
  • 1970-01-01
  • 2018-12-03
  • 1970-01-01
  • 2022-11-10
相关资源
最近更新 更多