pyautogui从终端工作但不是tkinter按钮

时间:2016-02-12 02:10:24

标签: python ubuntu tkinter pyautogui

晚上好, 我正在尝试学习一些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()

1 个答案:

答案 0 :(得分:0)

您有类似于此

的错误消息
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

您必须在功能global

中使用RunScript
def RunScript():
    global PauseStatus

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

def RunScript():
    PauseStatus = False