本文整理汇总了Python中RO.TkUtil.Timer.cancel方法的典型用法代码示例。如果您正苦于以下问题:Python Timer.cancel方法的具体用法?Python Timer.cancel怎么用?Python Timer.cancel使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类RO.TkUtil.Timer
的用法示例。
在下文中一共展示了Timer.cancel方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ObjPosWdg
# 需要导入模块: from RO.TkUtil import Timer [as 别名]
# 或者: from RO.TkUtil.Timer import cancel [as 别名]
#.........这里部分代码省略.........
self.tccModel.altLim.addCallback(self._altLimChanged)
# initialize display
self.restoreDefault()
self.objNameWdg.focus_set()
def _azLimChanged(self, azLim, isCurrent, **kargs):
# print "_azLimitChanged(azLim=%r, isCurrent=%s)" % (azLim, isCurrent)
coordSys = self.userModel.coordSysName.get()
if coordSys != RO.CoordSys.Mount:
return
self.objPos1.dataWdg.setRange(*azLim[0:2])
def _altLimChanged(self, altLim, isCurrent, **kargs):
# print "_altLimitChanged(altLim=%r, isCurrent=%s)" % (altLim, isCurrent)
coordSys = self.userModel.coordSysName.get()
if coordSys != RO.CoordSys.Mount:
return
self.objPos2.dataWdg.setRange(*altLim[0:2])
def _coordSysChanged (self, coordSys):
"""Update the display when the coordinate system is changed.
"""
# print "ObjPosWdg._coordSysChanged(coordSys=%r)" % (coordSys,)
pos1IsHours = 1
csysObj = RO.CoordSys.getSysConst(coordSys)
pos1IsHours = csysObj.eqInHours()
posLabels = csysObj.posLabels()
if coordSys in RO.CoordSys.AzAlt:
if coordSys == RO.CoordSys.Mount:
azLim, isCurrent = self.tccModel.azLim.get()
pos1Range = azLim[0:2]
altLim, isCurrent = self.tccModel.altLim.get()
pos2Range = altLim[0:2]
else:
pos1Range = (0, 360)
pos2Range = (0, 90)
elif pos1IsHours:
pos1Range = (0, 24)
pos2Range = (-90, 90)
else:
# no such coordsys, so makes a good sanity check
raise RuntimeError, "ObjPosWdg bug: cannot handle coordinate system %r" % (coordSys,)
self.objPos1.labelWdg["text"] = posLabels[0]
self.objPos2.labelWdg["text"] = posLabels[1]
self.objPos1.dataWdg.setIsHours(pos1IsHours)
self.objPos1.dataWdg.setRange(*pos1Range)
self.objPos2.dataWdg.setRange(*pos2Range)
def getSummary(self):
"""Returns (name, pos1, pos2, csys), all as the strings shown in the widgets
(not the numeric values).
It would be slightly nicer if the summary could be derived from the value dictionary
but this is quite tricky to do right."""
name = self.objNameWdg.get()
pos1 = self.objPos1.dataWdg.getString()
pos2 = self.objPos2.dataWdg.getString()
csys = self.userModel.coordSysName.get()
return (name, pos1, pos2, csys)
def neatenDisplay(self):
self.objPos1.dataWdg.neatenDisplay()
self.objPos2.dataWdg.neatenDisplay()
def setAzAltAirmass(self, *args, **kargs):
# print "ObjPosWdg.setAzAltAirmass"
self._azAltRefreshTimer.cancel()
target = self.userModel.potentialTarget.get()
if target == None:
self.azWdg.set(None)
self.altWdg.set(None)
self.airmassWdg.set(None)
return
azalt = target.getAzAlt()
if azalt == None:
self.azWdg.set(None)
self.altWdg.set(None)
self.airmassWdg.set(None)
return
az, alt = azalt
airmass = RO.Astro.Sph.airmass(alt)
altData, limCurrent = self.tccModel.altLim.get()
altSeverity = RO.Constants.sevNormal
minAlt = altData[0]
if minAlt != None:
if alt < minAlt:
altSeverity = RO.Constants.sevError
self.azWdg.set(az)
self.altWdg.set(alt, severity = altSeverity)
self.airmassWdg.set(airmass)
self._azAltRefreshTimer.start(_AzAltRefreshDelay, self.setAzAltAirmass)
示例2: WaitForTCPServer
# 需要导入模块: from RO.TkUtil import Timer [as 别名]
# 或者: from RO.TkUtil.Timer import cancel [as 别名]
class WaitForTCPServer(object):
"""Wait for a TCP server to accept a connection
"""
def __init__(self, host, port, callFunc, timeLim=5, pollInterval=0.2):
"""Start waiting for a TCP server to accept a connection
@param[in] host host address of server
@param[in] port port number of server
@param[in] callFunc function to call when server ready or wait times out;
receives one parameter: this object
@param[in] timeLim approximate maximum wait time (sec);
the actual wait time may be up to pollInterval longer
@param[in] pollInterval interval at which to poll (sec)
Useful attributes:
- isDone: the wait is over
- didFail: the wait failed
"""
self.host = host
self.port = port
self.isDone = False
self.didFail = False
self._callFunc = callFunc
self._pollInterval = float(pollInterval)
self._timeLim = float(timeLim)
self._pollTimer = Timer()
self._startTime = time.time()
self._tryConnection()
self._timeoutTimer = Timer(timeLim, self._finish)
def _tryConnection(self):
"""Attempt a connection
"""
self._sock = TCPSocket(host=self.host, port=self.port, stateCallback=self._sockStateCallback)
def _sockStateCallback(self, sock):
"""Socket state callback
"""
if sock.isReady:
# success
self._finish()
elif sock.isDone:
# connection failed; try again
self._pollTimer.start(self._pollInterval, self._tryConnection)
def _finish(self):
"""Set _isReady and call the callback function
"""
self._pollTimer.cancel()
self._timeoutTimer.cancel()
self.didFail = not self._sock.isReady
self.isDone = True
if not self._sock.isDone:
self._sock.setStateCallback()
self._sock.close()
self._sock = None
if self._callFunc:
callFunc = self._callFunc
self._callFunc = None
safeCall2("%s._finish" % (self,), callFunc, self)
def __repr__(self):
return "%s(host=%s, port=%s)" % (type(self).__name__, self.host, self.port)
示例3: __init__
# 需要导入模块: from RO.TkUtil import Timer [as 别名]
# 或者: from RO.TkUtil.Timer import cancel [as 别名]
class _BalloonHelp:
"""Show balloon help for any widget that has a helpText attribute
Help is shown delayMS after the mouse enters a widget or moves within a widget.
If help was showing within 0.6 sec of moving to a new widget then the help
for the new widget is shown immediately.
Help is hidden if the user clicks or types. However, the help timer is started again
if the mouse moves within the widget.
"""
def __init__(self, delayMS = 600):
"""Construct a _BalloonHelp
Inputs:
- delayMS: delay time before help is shown
"""
self._isShowing = False
self._delayMS = delayMS
self._showTimer = Timer()
self._leaveTimer = Timer()
self._msgWin = tkinter.Toplevel()
self._msgWin.overrideredirect(True)
self._msgWdg = tkinter.Message(self._msgWin, bg="light yellow")
self._msgWdg.pack()
self._msgWin.withdraw()
self._msgWdg.bind_all('<Motion>', self._start)
self._msgWdg.bind_all('<Leave>', self._leave)
self._msgWdg.bind_all('<ButtonPress>', self._stop)
self._msgWdg.bind_all('<KeyPress>', self._stop)
self._msgWdg.bind_all('<Tab>', self._stop, add=True)
self._msgWin.bind("<Configure>", self._configure)
def _configure(self, evt=None):
"""Callback for window Configure event
Using this flickers less than calling this from show (even using a short time delay).
Note: using self._isShowing is paranoia; the <Configure> event is only triggered
by show (which changes the message).
"""
if self._isShowing:
self._msgWin.tkraise()
self._msgWin.deiconify()
def _leave(self, evt=None):
"""Mouse has left a widget; start the leave timer if help is showing and stop showing help
"""
if self._isShowing:
self._leaveTimer.start(0.6, self._leaveDone)
self._stop()
def _leaveDone(self):
"""No-op for leave timer; can add a print statement for diagnostics
"""
pass
def _start(self, evt):
"""Start a timer to show the help in a bit.
If the help window is already showing, redisplay it immediately
"""
if self._isShowing:
return
self._isShowing = True
try:
if evt.widget.helpText and not self._showTimer.isActive:
# widget has help and the show timer is not already running
justLeft = self._leaveTimer.cancel()
if justLeft:
# recently left another widget while showing help; show help for this widget right away
delay = 0.001
else:
# not recently showing help; wait the usual time to show help
delay = self._delayMS / 1000.0
self._showTimer.start(delay, self._show, evt)
except AttributeError:
pass
def _show(self, evt):
"""Show help
"""
self._isShowing = True
x, y = evt.x_root, evt.y_root
self._msgWin.geometry("+%d+%d" % (x+10, y+10))
self._msgWdg["text"] = evt.widget.helpText
def _stop(self, evt=None):
"""Stop the timer and hide the help
"""
self._isShowing = False
self._showTimer.cancel()
self._msgWin.withdraw()
示例4: TestGuiderWdg
# 需要导入模块: from RO.TkUtil import Timer [as 别名]
# 或者: from RO.TkUtil.Timer import cancel [as 别名]
#.........这里部分代码省略.........
if self.isInstAgileWdg.getBool():
tccData = "inst=Agile"
else:
tccData = "inst=SPICam"
self.testDispatcher.dispatch(tccData, actor="tcc")
def dispatchFileData(self, wdg=None):
keyArgs = self.getDispatchKeyArgs("agileExpose", cmdID=0)
fileName = "image%d" % (self.fileNum,)
self.fileNum += 1
filesKeyword = makeFilesKeyword(cmdr=keyArgs["cmdr"], fileName=fileName)
self.testDispatcher.dispatch(filesKeyword, msgCode=":", **keyArgs)
def dispatchFindData(self, wdg=None):
keyArgs = self.getDispatchKeyArgs("afocus")
numToFind = self.numToFindWdg.getNum()
if numToFind < 1:
self.testDispatcher.dispatch("text='No stars found'", msgCode="f", **keyArgs)
return
mainXYPos = [wdg.getNum() for wdg in self.starPosWdgSet]
centroidRad = self.centroidRadWdg.getNum()
findData = makeFindData(numFound=numToFind, mainXYPos=mainXYPos, centroidRad=centroidRad)
self.testDispatcher.dispatch(findData, msgCode="i", **keyArgs)
self.testDispatcher.dispatch("", msgCode=":", **keyArgs)
def dispatchCentroidData(self, wdg=None):
keyArgs = self.getDispatchKeyArgs("afocus")
if not self.centroidOKWdg.getBool():
self.testDispatcher.dispatch("text='No stars found'", msgCode="f", **keyArgs)
return
xyPos = [wdg.getNum() for wdg in self.starPosWdgSet]
centroidRad = self.centroidRadWdg.getNum()
centroidData = makeStarKeyword(isFind=False, xyPos=xyPos, randRange=10, centroidRad=centroidRad)
self.testDispatcher.dispatch(centroidData, msgCode=":", **keyArgs)
def getDispatchKeyArgs(self, actor, cmdID=None):
"""Get keyword arguments for the test dispatcher's dispatch command
"""
if self.useWrongCmdrWdg.getBool():
cmdr = "APO.other"
else:
cmdr = self.tuiModel.getCmdr()
if cmdID is None:
if self.guideWdg.pendingCmd:
cmdID = self.guideWdg.pendingCmd.cmdID or 0
else:
cmdID = 0
if self.useWrongCmdIDWdg.getBool():
cmdID += 1000
if self.useWrongActorWdg.getBool():
actor = "other"
else:
actor = actor
return dict(cmdr=cmdr, cmdID=cmdID, actor=actor)
def pollPendingCmd(self):
"""Poll to see if there's a new pending command and respond accordingly
"""
self.pollTimer.cancel()
if self.guideWdg.pendingCmd != self.oldPendingCmd:
self.oldPendingCmd = self.guideWdg.pendingCmd
if not self.oldPendingCmd.isDone():
self.replyToCommand()
self.pollTimer.start(1.0, self.pollPendingCmd)
def replyToCommand(self):
"""Issue the appropriate replly to a pending command
"""
# print "replyToCommand", self.oldPendingCmd
actor = self.oldPendingCmd.actor.lower()
cmdStr = self.oldPendingCmd.cmdStr
cmdID = self.oldPendingCmd.cmdID
keyArgs = self.getDispatchKeyArgs(actor)
if actor == "tcc":
if self.offsetOKWdg.getBool():
self.testDispatcher.dispatch("", msgCode=":", **keyArgs)
else:
self.testDispatcher.dispatch("text='Offset failed'", msgCode="f", **keyArgs)
elif actor == "afocus":
if cmdStr.startswith("centroid"):
self.dispatchCentroidData()
elif cmdStr.startswith("find"):
self.dispatchFindData()
else:
print "Unknown afocus command:", cmdStr
else:
print "Unknown actor:", actor
示例5: FTPLogWdg
# 需要导入模块: from RO.TkUtil import Timer [as 别名]
# 或者: from RO.TkUtil.Timer import cancel [as 别名]
#.........这里部分代码省略.........
if omitted, an ftp URL (with no username/password) is created
- username the usual; *NOT SECURE*
- password the usual; *NOT SECURE*
"""
# print "getFile(%r, %r, %r)" % (host, fromPath, toPath)
stateLabel = RO.Wdg.StrLabel(self, anchor="w", width=FTPGet.StateStrMaxLen)
ftpGet = FTPGet(
host = host,
fromPath = fromPath,
toPath = toPath,
isBinary = isBinary,
overwrite = overwrite,
createDir = createDir,
startNow = False,
dispStr = dispStr,
username = username,
password = password,
)
self._trackMem(ftpGet, "ftpGet(%s)" % (fromPath,))
# display item and append to list
# (in that order so we can test for an empty list before displaying)
if self.dispList:
# at least one item is shown
self.text.insert("end", "\n")
doAutoSelect = self.selFTPGet in (self.dispList[-1], None)
else:
doAutoSelect = True
self.text.window_create("end", window=stateLabel)
self.text.insert("end", ftpGet.dispStr)
self.dispList.append(ftpGet)
self._timer.cancel()
# append ftpGet to the queue
ftpCallback = FTPCallback(ftpGet, callFunc)
self.getQueue.append((ftpGet, stateLabel, ftpCallback))
# purge old display items if necessary
ind = 0
selInd = None
while max(self.maxLines, ind) < len(self.dispList):
#print "FTPLogWdg.getFile: maxLines=%s, ind=%s, nEntries=%s" % (self.maxLines, ind, len(self.dispList),)
# only erase entries for files that are finished
if not self.dispList[ind].isDone:
#print "FTPLogWdg.getFile: file at ind=%s is not done" % (ind,)
ind += 1
continue
#print "FTPLogWdg.getFile: purging entry at ind=%s" % (ind,)
if (not doAutoSelect) and (self.selFTPGet == self.dispList[ind]):
selInd = ind
#print "FTPLogWdg.getFile: purging currently selected file; saving index"
del(self.dispList[ind])
self.text.delete("%d.0" % (ind+1,), "%d.0" % (ind+2,))
# if one of the purged items was selected,
# select the next down extant item
# auto scroll
if doAutoSelect:
self._selectInd(-1)
self.text.see("end")
elif selInd is not None:
示例6: UsersWdg
# 需要导入模块: from RO.TkUtil import Timer [as 别名]
# 或者: from RO.TkUtil.Timer import cancel [as 别名]
class UsersWdg(Tkinter.Frame):
"""Display the current users and those recently logged out.
Inputs:
- master parent widget
- retainSec time to retain information about logged out users (sec)
- height default height of text widget
- width default width of text widget
- other keyword arguments are used for the frame
"""
def __init__ (self,
master=None,
retainSec=300,
height = 10,
width = 50,
**kargs):
Tkinter.Frame.__init__(self, master, **kargs)
hubModel = TUI.Models.HubModel.getModel()
self.tuiModel = TUI.TUIModel.getModel()
# entries are commanders (prog.user)
self._cmdrList = []
# entries are (cmdr, time deleted); time is from time.time()
self._delCmdrTimeList = []
# time to show deleted users
self._retainSec = retainSec
# dictionary of user name: User object
self.userDict = dict()
self._updateTimer = Timer()
self.yscroll = Tkinter.Scrollbar (
master = self,
orient = "vertical",
)
self.text = Tkinter.Text (
master = self,
yscrollcommand = self.yscroll.set,
wrap = "none",
tabs = "1.6c 5.0c 6.7c 8.5c",
height = height,
width = width,
)
self.yscroll.configure(command=self.text.yview)
self.text.grid(row=0, column=0, sticky="nsew")
self.yscroll.grid(row=0, column=1, sticky="ns")
RO.Wdg.Bindings.makeReadOnly(self.text)
RO.Wdg.addCtxMenu(
wdg = self.text,
helpURL = _HelpPage,
)
self.rowconfigure(0, weight=1)
self.columnconfigure(0, weight=1)
self.text.tag_configure("del", overstrike=True)
self.text.tag_configure("me", underline=True)
hubModel.user.addCallback(self.updUser, callNow=False)
hubModel.users.addCallback(self.updUsers)
def scheduleUpdate(self, afterSec=1.0):
"""Schedule a new update
"""
self._updateTimer.start(afterSec, self.updDisplay)
def updDisplay(self):
"""Display current data.
"""
self._updateTimer.cancel()
myCmdr = self.tuiModel.getCmdr()
maxDisplayTime = time.time() - self._retainSec
self.text.delete("1.0", "end")
doScheduleUpdate = False
deleteCmdrList = []
for cmdr in sorted(self.userDict.keys()):
userObj = self.userDict[cmdr]
if userObj.clientName == "monitor":
continue
if userObj.isConnected:
tagList = ["curr"]
elif userObj.disconnTime < maxDisplayTime:
deleteCmdrList.append(cmdr)
continue
else:
tagList = ["del"]
doScheduleUpdate = True
if cmdr == myCmdr:
tagList.append("me")
displayStr = "%s\t%s\t%s\t%s\t%s\n" % \
(userObj.prog, userObj.user, userObj.clientName, userObj.clientVersion, userObj.systemInfo)
self.text.insert("end", displayStr, " ".join(tagList))
for cmdr in deleteCmdrList:
del(self.userDict[cmdr])
#.........这里部分代码省略.........
示例7: PrefEditor
# 需要导入模块: from RO.TkUtil import Timer [as 别名]
# 或者: from RO.TkUtil.Timer import cancel [as 别名]
#.........这里部分代码省略.........
def getInitialValue(self):
return self.initialValue
def setVariable(self):
"""Sets the preference variable to the edit value"""
self.prefVar.setValue(self.getEditValue())
self.updateChanged()
def showValue(self, value):
self.editVar.set(value)
self.updateEditor()
def showCurrentValue(self):
self.showValue(self.getCurrentValue())
def showDefaultValue(self):
self.showValue(self.getDefValue())
def showInitialValue(self):
self.showValue(self.getInitialValue())
def unappliedChanges(self):
"""Returns true if the user has changed the value and it has not been applied"""
return self.getEditValue() != self.prefVar.getValueStr()
def updateEditor(self):
"""Called after editVal is changed (and verified)"""
pass
def updateChanged(self):
"""Updates the "value changed" indicator.
"""
self.timer.cancel()
editValue = self.getEditValue()
# print "updateChanged called"
# print "editValue = %r" % editValue
# print "currentValue = %r" % self.getCurrentValue()
# print "initialValue = %r" % self.getInitialValue()
# print "defaultValue = %r" % self.getDefValue()
if editValue == self.getCurrentValue():
self.changedVar.set("")
else:
self.changedVar.set("!")
def _addCtxMenu(self, wdg):
"""Convenience function; adds the usual contextual menu to a widget"""
RO.Wdg.addCtxMenu (
wdg = wdg,
helpURL = self.prefVar.helpURL,
configFunc = self._configCtxMenu,
)
wdg.helpText = self.prefVar.helpText
def _editCallback(self, *args):
"""Called whenever the edited value changes.
Uses after to avoid the problem of the user entering
an invalid character that is immediately rejected;
that rejection doesn't show up in editVar.get
and so the changed indicator falsely turns on.
"""
# print "_editCallback; afterID=", self.afterID
self.timer.start(0.001, self.updateChanged)
def _setupCallbacks(self):
"""Set up a callback to call self.updateChanged
示例8: DropletRunner
# 需要导入模块: from RO.TkUtil import Timer [as 别名]
# 或者: from RO.TkUtil.Timer import cancel [as 别名]
class DropletRunner(object):
"""Run a script as a droplet (an application onto which you drop file) with a log window.
Data the script writes to sys.stdout and sys.stderr is written to a log window;
stderr output is shown in red.
On Mac OS X additional files may be dropped on the application icon once the first batch is processed.
I don't know how to support this on other platforms.
"""
def __init__(self, scriptPath, title=None, initialText=None, **keyArgs):
"""Construct and run a DropletRunner
Inputs:
- scriptPath: path to script to run when files are dropped on the application
- title: title for log window; if None then generated from scriptPath
- initialText: initial text to display in log window
**keyArgs: all other keyword arguments are sent to the RO.Wdg.LogWdg constructor
"""
self.isRunning = False
self.scriptPath = os.path.abspath(scriptPath)
if not os.path.isfile(scriptPath):
raise RuntimeError("Cannot find script %r" % (self.scriptPath,))
self.tkRoot = tkinter.Tk()
self._timer = Timer()
if title is None:
title = os.path.splitext(os.path.basename(scriptPath))[0]
self.tkRoot.title(title)
if RO.OS.PlatformName == "mac":
self.tkRoot.createcommand('::tk::mac::OpenDocument', self._macOpenDocument)
# the second argument is a process ID (approximately) if run as an Applet;
# the conditional handles operation from the command line
if len(sys.argv) > 1 and sys.argv[1].startswith("-"):
filePathList = sys.argv[2:]
else:
filePathList = sys.argv[1:]
else:
filePathList = sys.argv[1:]
self.logWdg = LogWdg.LogWdg(self.tkRoot, **keyArgs)
self.logWdg.grid(row=0, column=0, sticky="nsew")
self.tkRoot.grid_rowconfigure(0, weight=1)
self.tkRoot.grid_columnconfigure(0, weight=1)
if initialText:
self.logWdg.addOutput(initialText)
if filePathList:
self.runFiles(filePathList)
self.tkRoot.mainloop()
def runFiles(self, filePathList):
"""Run the script with the specified files
"""
# print "runFiles(filePathList=%s)" % (filePathList,)
self.isRunning = True
argList = [sys.executable, self.scriptPath] + list(filePathList)
self.subProc = subprocess.Popen(argList, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self.tkRoot.tk.createfilehandler(self.subProc.stderr, tkinter.READABLE, self._readStdErr)
self.tkRoot.tk.createfilehandler(self.subProc.stdout, tkinter.READABLE, self._readStdOut)
self._poll()
def _macOpenDocument(self, *filePathList):
"""Handle Mac OpenDocument event
"""
self.runFiles(filePathList)
def _poll(self):
"""Poll for subprocess completion
"""
if self.subProc.returncode is not None:
self._cleanup()
else:
self._timer(0.1, self._poll)
def _readStdOut(self, *dumArgs):
"""Read and log data from script's stdout
"""
self.logWdg.addOutput(self.subProc.stdout.read())
if self.subProc.poll() is not None:
self._cleanup()
def _readStdErr(self, *dumArgs):
"""Read and log data from script's stderr
"""
self.logWdg.addOutput(self.subProc.stderr.read(), severity=RO.Constants.sevError)
if self.subProc.poll() is not None:
self._cleanup()
def _cleanup(self):
"""Close Tk file handlers and print any final data from the subprocess
"""
self._timer.cancel()
if self.isRunning:
self.isRunning = False
self.tkRoot.tk.deletefilehandler(self.subProc.stdout)
self.tkRoot.tk.deletefilehandler(self.subProc.stderr)
#.........这里部分代码省略.........
示例9: StatusConfigInputWdg
# 需要导入模块: from RO.TkUtil import Timer [as 别名]
# 或者: from RO.TkUtil.Timer import cancel [as 别名]
#.........这里部分代码省略.........
nameSep = " move=",
)
# set up the input container set
self.inputCont = RO.InputCont.ContList (
conts = [
RO.InputCont.WdgCont (
name = "calmirror",
wdgs = self.calMirror.userWdg,
formatFunc = RO.InputCont.BasicFmt(nameSep=" "),
),
RO.InputCont.WdgCont (
name = "collimator",
wdgs = self.collimator.userWdg,
formatFunc = moveFmtFunc,
),
RO.InputCont.WdgCont (
name = "disperser",
wdgs = self.disperser.userWdg,
formatFunc = moveFmtFunc,
),
RO.InputCont.WdgCont (
name = "filter",
wdgs = self.filter.userWdg,
formatFunc = moveFmtFunc,
),
RO.InputCont.WdgCont (
name = "lenslets",
wdgs = self.lenslets.userWdg,
formatFunc = moveFmtFunc,
),
RO.InputCont.WdgCont (
name = "magnifier",
wdgs = self.magnifier.userWdg,
formatFunc = moveFmtFunc,
),
],
)
self._inputContNameKeyVarDict = dict(
calmirror = self.model.calMirrorPresets,
collimator = self.model.collimatorPresets,
disperser = self.model.disperserPresets,
filter = self.model.filterPresets,
lenslets = self.model.lensletPresets,
magnifier = self.model.magnifierPresets,
)
self.presetsWdg = RO.Wdg.InputContPresetsWdg(
master = self,
sysName = "%sConfig" % (self.InstName,),
userPresetsDict = self.tuiModel.userPresetsDict,
inputCont = self.inputCont,
helpText = "use and manage named presets",
helpURL = self.HelpPrefix + "Presets",
)
self.gridder.gridWdg(
"Presets",
cfgWdg = self.presetsWdg,
)
self.gridder.allGridded()
# for presets data use a timer to increase the chance that all keywords have been seen
# before the method is called
def callUpdPresets(*args, **kwargs):
self.updateStdPresetsTimer.start(0.1, self.updateStdPresets)
for keyVar in self._inputContNameKeyVarDict.itervalues():
keyVar.addCallback(callUpdPresets)
def repaint(evt):
self.restoreDefault()
self.bind("<Map>", repaint)
def updateStdPresets(self):
"""Update standard presets, if the data is available
"""
self.updateStdPresetsTimer.cancel()
nameList = self.model.namePresets.get()[0]
if None in nameList:
return
numPresets = len(nameList)
dataDict = dict()
for inputContName, keyVar in self._inputContNameKeyVarDict.iteritems():
valList = keyVar.get()[0]
if len(valList) != numPresets or None in valList:
return
dataDict[inputContName] = valList
# stdPresets is a dict of name: dict of input container name: value
stdPresets = dict()
for i, name in enumerate(nameList):
contDict = dict()
for inputContName, valList in dataDict.iteritems():
if not valList[i]:
continue
contDict[inputContName] = valList[i]
if contDict:
stdPresets[name] = contDict
self.presetsWdg.setStdPresets(stdPresets)
示例10: TimeBar
# 需要导入模块: from RO.TkUtil import Timer [as 别名]
# 或者: from RO.TkUtil.Timer import cancel [as 别名]
class TimeBar(ProgressBar):
"""Progress bar to display elapsed or remaining time in seconds.
Inputs:
- countUp: if True, counts up, else counts down
- autoStop: automatically stop when the limit is reached
- updateInterval: how often to update the display (sec)
**kargs: other arguments for ProgressBar, including:
- value: initial time;
typically 0 for a count up timer, maxValue for a countdown timer
if omitted then 0 is shown and the bar does not progress until you call start.
- minvalue: minimum time; typically 0
- maxValue: maximum time
"""
def __init__ (self,
master,
countUp = False,
valueFormat = ("%3.0f sec", "??? sec"),
autoStop = False,
updateInterval = 0.1,
**kargs):
ProgressBar.__init__(self,
master = master,
valueFormat = valueFormat,
**kargs
)
self._autoStop = bool(autoStop)
self._countUp = bool(countUp)
self._updateInterval = updateInterval
self._updateTimer = Timer()
self._startTime = None
if "value" in kargs:
self.start(kargs["value"])
def clear(self):
"""Set the bar length to zero, clear the numeric time display and stop the timer.
"""
self._updateTimer.cancel()
ProgressBar.clear(self)
self._startTime = None
def pause(self, value = None):
"""Pause the timer.
Inputs:
- value: the value at which to pause; if omitted then the current value is used
Error conditions: does nothing if not running.
"""
if self._updateTimer.cancel():
# update timer was running
if value:
self.setValue(value)
else:
self._updateTime(reschedule = False)
def resume(self):
"""Resume the timer from the current value.
Does nothing if not paused or running.
"""
if self._startTime is None:
return
self._startUpdate()
def start(self, value = None, newMin = None, newMax = None, countUp = None):
"""Start the timer.
Inputs:
- value: starting value; if None, set to 0 if counting up, max if counting down
- newMin: minimum value; if None then the existing value is used
- newMax: maximum value: if None then the existing value is used
- countUp: if True/False then count up/down; if None then the existing value is used
Typically you will only specify newMax or nothing.
"""
if newMin is not None:
self.minValue = float(newMin)
if newMax is not None:
self.maxValue = float(newMax)
if countUp is not None:
self._countUp = bool(countUp)
if value is not None:
value = float(value)
elif self._countUp:
value = 0.0
else:
value = self.maxValue
self.setValue(value)
self._startUpdate()
def _startUpdate(self):
"""Starts updating from the current value.
"""
if self._countUp:
self._startTime = time.time() - self.value
else:
#.........这里部分代码省略.........