本文整理汇总了Python中RO.TkUtil.Timer类的典型用法代码示例。如果您正苦于以下问题:Python Timer类的具体用法?Python Timer怎么用?Python Timer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Timer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
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)
示例2: __init__
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)
示例3: __init__
def __init__(self,
prefVar,
master,
row = 0,
column = 0,
):
self.master = master
self.prefVar = prefVar
# create and set a variable to contain the edited value
self.editVar = tkinter.StringVar()
self.editVar.set(self.prefVar.getValueStr())
# save initial value, in case we have to restore it
self.initialValue = self.getCurrentValue()
# save last good value, for use if a typed char is rejected
self.mostRecentValidValue = self.editVar.get()
# a list (in grid order) of (widget name, sticky setting)
wdgInfo = (
("labelWdg", "e"),
("changedWdg", ""),
("editWdg", "w"),
("unitsWdg", "w"),
)
self.labelWdg = tkinter.Label(self.master, text = self.prefVar.name)
self._addCtxMenu(self.labelWdg)
self.changedVar = tkinter.StringVar()
self.changedWdg = tkinter.Label(self.master, width=1, textvariable=self.changedVar)
self._addCtxMenu(self.changedWdg)
self.editWdg = self._getEditWdg()
# self.rangeWdg = self._getRangeWdg()
if self.prefVar.units:
self.unitsWdg = tkinter.Label(self.master, text = self.prefVar.name)
self._addCtxMenu(self.unitsWdg)
else:
self.unitsWdg = None
# grid the widgets
for wdgName, sticky in wdgInfo:
wdg = getattr(self, wdgName)
if wdg:
wdg.grid(row=row, column=column, sticky=sticky)
column += 1
self.timer = Timer()
self._setupCallbacks()
示例4: __init__
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)
示例5: __init__
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()
示例6: __init__
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"])
示例7: __init__
def __init__ (self, master=None, **kargs):
"""Displays miscellaneous information, such as current time and az/alt
Inputs:
- master master Tk widget -- typically a frame or window
"""
Tkinter.Frame.__init__(self, master=master, **kargs)
self.tccModel = TUI.TCC.TCCModel.getModel()
self.gmechModel = TUI.Guide.GMechModel.getModel()
self._clockTimer = Timer()
gr = RO.Wdg.Gridder(self, sticky="e")
# magic numbers
AzAltRotPrec = 1 # number of digits past decimal point
self.haWdg = RO.Wdg.DMSLabel(
master = self,
precision = 0,
nFields = 3,
cvtDegToHrs = 1,
width = 8,
helpText = "Hour angle of the object",
helpURL = _HelpURL,
)
gr.gridWdg (
label = "HA",
dataWdg = self.haWdg,
units = "hms",
)
self.lmstWdg = RO.Wdg.DMSLabel(
master = self,
precision = 0,
nFields = 3,
width = 8,
justify="right",
helpText = "Local mean sidereal time at APO",
helpURL = _HelpURL,
)
gr.gridWdg (
label = "LMST",
dataWdg = self.lmstWdg,
units = "hms",
)
self.utcWdg = RO.Wdg.StrLabel(
master = self,
width = 19,
helpText = "Coordinated universal time",
helpURL = _HelpURL,
)
gr.gridWdg (
label = "UTC",
dataWdg = self.utcWdg,
colSpan = 2,
)
# start the second column of widgets
gr.startNewCol(spacing=1)
self.guideWdg = RO.Wdg.StrLabel(
master = self,
width = 13,
anchor = "w",
helpText = "State of guiding",
helpURL = _HelpURL,
)
gr.gridWdg (
label = "Guiding",
dataWdg = self.guideWdg,
colSpan = 4,
units = False,
sticky = "ew",
)
gr._nextCol -= 2 # allow overlap with widget to the right
self.guideModelDict = {} # guide camera name: guide model
for guideModel in TUI.Guide.GuideModel.modelIter():
gcamName = guideModel.gcamName
if gcamName.endswith("focus"):
continue
self.guideModelDict[guideModel.gcamName] = guideModel
guideModel.locGuideStateSummary.addIndexedCallback(self._updGuideStateSummary, callNow=False)
self._updGuideStateSummary()
# airmass and zenith distance
self.airmassWdg = RO.Wdg.FloatLabel(
master = self,
precision=3,
width=5,
helpURL = _HelpURL,
)
gr.gridWdg (
label = "Airmass",
dataWdg = self.airmassWdg,
units = "",
)
# self.tccModel.axePos.addCallback(self.setAxePos)
#.........这里部分代码省略.........
示例8: __init__
def __init__ (self, master=None, **kargs):
"""Displays miscellaneous information, such as current time and az/alt
Inputs:
- master master Tk widget -- typically a frame or window
"""
Tkinter.Frame.__init__(self, master=master, **kargs)
self.tccModel = TUI.Models.getModel("tcc")
self.guiderModel = TUI.Models.getModel("guider")
self.mcpModel = TUI.Models.getModel("mcp")
self.plateDBModel = TUI.Models.getModel("platedb")
self._cartridgeInfo = [None]*3 # (cartID, plateID, pointing)
self._clockTimer = Timer()
gr = RO.Wdg.Gridder(self, sticky="e")
self.haWdg = RO.Wdg.DMSLabel(
master = self,
precision = 0,
nFields = 3,
cvtDegToHrs = 1,
width = 8,
helpText = "Hour angle of the object",
helpURL = _HelpURL,
)
gr.gridWdg("HA", self.haWdg, "hms")
self.designHAWdg = RO.Wdg.DMSLabel(
master = self,
precision = 0,
nFields = 3,
cvtDegToHrs = 1,
width = 8,
helpText = "Hour angle the plate was designed for (from platedb)",
helpURL = _HelpURL,
)
gr.gridWdg("Design HA", self.designHAWdg, "hms")
self.deltaHAWdg = RO.Wdg.DMSLabel(
master = self,
precision = 0,
nFields = 3,
cvtDegToHrs = 1,
width = 8,
helpText = "Design - current hour angle",
helpURL = _HelpURL,
)
gr.gridWdg("Des-Curr HA", self.deltaHAWdg, "hms")
self.taiWdg = RO.Wdg.StrLabel(
master = self,
width=19,
helpText = "International Atomic Time",
helpURL = _HelpURL,
)
gr.gridWdg("TAI", self.taiWdg, colSpan=2)
# secondary focus
self.secFocusWdg = RO.Wdg.FloatLabel(
master = self,
precision = 0,
width = 5,
helpText = "Secondary mirror focus",
helpURL = _HelpURL,
)
gr.gridWdg (
label = "Focus",
dataWdg = self.secFocusWdg,
units = u"\N{MICRO SIGN}m",
)
self.tccModel.secFocus.addValueCallback(self.secFocusWdg.set)
# start the second column of widgets
gr.startNewCol(spacing=1)
gr._nextCol -= 2 # allow overlap with widget to the right
self.airmassWdg = RO.Wdg.FloatLabel(
master = self,
precision=3,
width = 5,
helpText = "Airmass",
helpURL = _HelpURL,
)
gr.gridWdg("Airmass", self.airmassWdg)
self.zdWdg = RO.Wdg.FloatLabel(
master = self,
precision = 1,
helpText = "Zenith distance (90 - altitude)",
helpURL = _HelpURL,
width = 5,
)
gr.gridWdg("ZD", self.zdWdg, RO.StringUtil.DegStr)
self.lmstWdg = RO.Wdg.DMSLabel(
master = self,
precision = 0,
nFields = 3,
width = 8,
#.........这里部分代码省略.........
示例9: MiscWdg
class MiscWdg (Tkinter.Frame):
def __init__ (self, master=None, **kargs):
"""Displays miscellaneous information, such as current time and az/alt
Inputs:
- master master Tk widget -- typically a frame or window
"""
Tkinter.Frame.__init__(self, master=master, **kargs)
self.tccModel = TUI.TCC.TCCModel.getModel()
self.gmechModel = TUI.Guide.GMechModel.getModel()
self._clockTimer = Timer()
gr = RO.Wdg.Gridder(self, sticky="e")
# magic numbers
AzAltRotPrec = 1 # number of digits past decimal point
self.haWdg = RO.Wdg.DMSLabel(
master = self,
precision = 0,
nFields = 3,
cvtDegToHrs = 1,
width = 8,
helpText = "Hour angle of the object",
helpURL = _HelpURL,
)
gr.gridWdg (
label = "HA",
dataWdg = self.haWdg,
units = "hms",
)
self.lmstWdg = RO.Wdg.DMSLabel(
master = self,
precision = 0,
nFields = 3,
width = 8,
justify="right",
helpText = "Local mean sidereal time at APO",
helpURL = _HelpURL,
)
gr.gridWdg (
label = "LMST",
dataWdg = self.lmstWdg,
units = "hms",
)
self.utcWdg = RO.Wdg.StrLabel(
master = self,
width = 19,
helpText = "Coordinated universal time",
helpURL = _HelpURL,
)
gr.gridWdg (
label = "UTC",
dataWdg = self.utcWdg,
colSpan = 2,
)
# start the second column of widgets
gr.startNewCol(spacing=1)
self.guideWdg = RO.Wdg.StrLabel(
master = self,
width = 13,
anchor = "w",
helpText = "State of guiding",
helpURL = _HelpURL,
)
gr.gridWdg (
label = "Guiding",
dataWdg = self.guideWdg,
colSpan = 4,
units = False,
sticky = "ew",
)
gr._nextCol -= 2 # allow overlap with widget to the right
self.guideModelDict = {} # guide camera name: guide model
for guideModel in TUI.Guide.GuideModel.modelIter():
gcamName = guideModel.gcamName
if gcamName.endswith("focus"):
continue
self.guideModelDict[guideModel.gcamName] = guideModel
guideModel.locGuideStateSummary.addIndexedCallback(self._updGuideStateSummary, callNow=False)
self._updGuideStateSummary()
# airmass and zenith distance
self.airmassWdg = RO.Wdg.FloatLabel(
master = self,
precision=3,
width=5,
helpURL = _HelpURL,
)
gr.gridWdg (
label = "Airmass",
dataWdg = self.airmassWdg,
units = "",
)
# self.tccModel.axePos.addCallback(self.setAxePos)
#.........这里部分代码省略.........
示例10: AxisStatusWdg
class AxisStatusWdg(Tkinter.Frame):
def __init__ (self, master=None, **kargs):
"""Displays information about the axes
Inputs:
- master master Tk widget -- typically a frame or window
"""
Tkinter.Frame.__init__(self, master=master, **kargs)
self.tccModel = TUI.TCC.TCCModel.getModel()
self.prevSounds = [None]*3 # sounds played last time we received AxisCmdState
self.prevCtrlStatusOK = [None]*3
self.ctrlBadTime = 0 # time of last "controller bad" sound
self._soundTimer = Timer()
# magic numbers
PosPrec = 1 # number of digits past decimal point
PosWidth = 5 + PosPrec # assumes -999.99... degrees is longest field
AxisCmdStateWidth = 8
AxisErrCodeWidth = 13
CtrlStatusWidth = 25
self.axisInd = range(len(self.tccModel.axisNames))
# actual axis position widget set
self.axePosWdgSet = [
RO.Wdg.FloatLabel(
master = self,
precision = PosPrec,
width = PosWidth,
helpText = "Current axis position, as reported by the controller",
helpURL = _HelpURL,
)
for axis in self.axisInd
]
self.tccModel.axePos.addROWdgSet(self.axePosWdgSet)
# target axis position widget set
self.tccPosWdgSet = [
RO.Wdg.FloatLabel(
master = self,
precision = PosPrec,
width = PosWidth,
helpText = "Target axis position",
helpURL = _HelpURL,
)
for axis in self.axisInd
]
self.tccModel.tccPos.addROWdgSet(self.tccPosWdgSet)
# TCC status widget set (e.g. tracking or halted)
self.axisCmdStateWdgSet = [
RO.Wdg.StrLabel(
master = self,
width = AxisCmdStateWidth,
helpText = "What the TCC is telling the axis to do",
helpURL = _HelpURL,
anchor = "nw",
)
for axis in self.axisInd
]
self.tccModel.axisCmdState.addCallback(self.setAxisCmdState)
self.tccModel.rotExists.addIndexedCallback(self.setRotExists)
# axis error code widet set (why the TCC is not moving the axis)
self.axisErrCodeWdgSet = [
RO.Wdg.StrLabel(
master = self,
width = AxisErrCodeWidth,
helpText = "Why the TCC halted the axis",
helpURL = _HelpURL,
anchor = "nw",
)
for axis in self.axisInd
]
self.tccModel.axisErrCode.addROWdgSet(self.axisErrCodeWdgSet)
# controller status widget set (the status word)
self.ctrlStatusWdgSet = [
RO.Wdg.StrLabel(
master = self,
width = CtrlStatusWidth,
helpText = "Status reported by the axis controller",
helpURL = _HelpURL,
anchor = "nw",
)
for axis in self.axisInd
]
for axis in self.axisInd:
self.tccModel.ctrlStatusSet[axis].addIndexedCallback(
RO.Alg.GenericCallback(self.setCtrlStatus, axis), 3)
# grid the axis widgets
gr = RO.Wdg.Gridder(self, sticky="w")
for axis in self.axisInd:
unitsLabel1 = Tkinter.Label(self, text=RO.StringUtil.DegStr)
unitsLabel2 = Tkinter.Label(self, text=RO.StringUtil.DegStr)
if axis == 2:
self.rotUnitsLabel1 = unitsLabel1
#.........这里部分代码省略.........
示例11: MiscWdg
class MiscWdg (Tkinter.Frame):
InstNameDict = {0: "None"} # add a value for Eng Cam once known
def __init__ (self, master=None, **kargs):
"""Displays miscellaneous information, such as current time and az/alt
Inputs:
- master master Tk widget -- typically a frame or window
"""
Tkinter.Frame.__init__(self, master=master, **kargs)
self.tccModel = TUI.Models.getModel("tcc")
self.guiderModel = TUI.Models.getModel("guider")
self.mcpModel = TUI.Models.getModel("mcp")
self.plateDBModel = TUI.Models.getModel("platedb")
self._cartridgeInfo = [None]*3 # (cartID, plateID, pointing)
self._clockTimer = Timer()
gr = RO.Wdg.Gridder(self, sticky="e")
self.haWdg = RO.Wdg.DMSLabel(
master = self,
precision = 0,
nFields = 3,
cvtDegToHrs = 1,
width = 8,
helpText = "Hour angle of the object",
helpURL = _HelpURL,
)
gr.gridWdg("HA", self.haWdg, "hms")
self.designHAWdg = RO.Wdg.DMSLabel(
master = self,
precision = 0,
nFields = 3,
cvtDegToHrs = 1,
width = 8,
helpText = "Hour angle the plate was designed for (from platedb)",
helpURL = _HelpURL,
)
gr.gridWdg("Design HA", self.designHAWdg, "hms")
self.deltaHAWdg = RO.Wdg.DMSLabel(
master = self,
precision = 0,
nFields = 3,
cvtDegToHrs = 1,
width = 8,
helpText = "Design - current hour angle",
helpURL = _HelpURL,
)
gr.gridWdg("Des-Curr HA", self.deltaHAWdg, "hms")
self.taiWdg = RO.Wdg.StrLabel(
master = self,
width=19,
helpText = "International Atomic Time",
helpURL = _HelpURL,
)
gr.gridWdg("TAI", self.taiWdg, colSpan=2)
# secondary focus
self.secFocusWdg = RO.Wdg.FloatLabel(
master = self,
precision = 0,
width = 5,
helpText = "Secondary mirror focus",
helpURL = _HelpURL,
)
gr.gridWdg (
label = "Focus",
dataWdg = self.secFocusWdg,
units = u"\N{MICRO SIGN}m",
)
self.tccModel.secFocus.addValueCallback(self.secFocusWdg.set)
# start the second column of widgets
gr.startNewCol(spacing=1)
gr._nextCol -= 2 # allow overlap with widget to the right
self.airmassWdg = RO.Wdg.FloatLabel(
master = self,
precision=3,
width = 5,
helpText = "Airmass",
helpURL = _HelpURL,
)
gr.gridWdg("Airmass", self.airmassWdg)
self.zdWdg = RO.Wdg.FloatLabel(
master = self,
precision = 1,
helpText = "Zenith distance (90 - altitude)",
helpURL = _HelpURL,
width = 5,
)
gr.gridWdg("ZD", self.zdWdg, RO.StringUtil.DegStr)
self.lmstWdg = RO.Wdg.DMSLabel(
master = self,
precision = 0,
#.........这里部分代码省略.........
示例12: getFile
def getFile(self,
host,
fromPath,
toPath,
isBinary = True,
overwrite = False,
createDir = True,
callFunc = None,
dispStr = None,
username = None,
password = None,
):
"""Get a file
Inputs:
- host IP address of ftp host
- fromPath full path of file on host to retrieve
- toPath full path of destination file
- isBinary file is binary? (if False, EOL translation is probably performed)
- overwrite: if True, overwrites the destination file if it exists;
otherwise raises ValueError
- createDir: if True, creates any required directories;
otherwise raises ValueError
- callFunc: called whenever more data is read or the state changes;
receives one argument: an RO.Comm.FTPGet.FTPGet object.
- dispStr a string to display while downloading the file;
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 = Timer()
# 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 != None:
self._selectInd(selInd)
示例13: WaitForTCPServer
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)
示例14: SkyWdg
class SkyWdg (Tkinter.Frame):
TELCURRENT = "telCurrent"
TELTARGET = "telTarget"
TELPOTENTIAL = "telPotential"
CATOBJECT = "catObject"
AzWrapSpiralDRad = 10
AzWrapItemRad = 3
AzWrapMargin = 5
AzAltMargin = 10
def __init__(self, master, width=201, height=201):
Tkinter.Frame.__init__(self, master)
self.tuiModel = TUI.TUIModel.getModel()
self.tccModel = TUI.TCC.TCCModel.getModel()
self.userModel = TUI.TCC.UserModel.getModel()
# instance variables:
# center: position of center of canvas, in pixels
# size: size of canvas, in pixels
# scale: scale of canvas, in pixels per deg
self.currCatObjID = None
self._telPotentialAnimTimer = Timer()
self.eastLabelPos = AzAltTarget(azAlt=(90, 0))
self.northLabelPos = AzAltTarget(azAlt=(180, 0))
# pane on which to display current star info
self.currStarDisp = RO.Wdg.StatusBar(master=self)
self.currStarDisp.grid(row=1, column=0, sticky="ew")
self.currStarMsgID = None
# canvas on which to display stars
self.cnv = Tkinter.Canvas(master=self,
width=width, height=height,
# background='black',
selectborderwidth=0, highlightthickness=0)
self.cnv.grid(row=0, column=0, sticky="nsew")
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
RO.Wdg.addCtxMenu(
wdg = self.cnv,
helpURL = _HelpURL,
)
# thickness of canvas border;
# drawable width/height = winfo_width/height - (2 * border)
self.cnvBorderWidth = int(self.cnv["highlightthickness"]) + int(self.cnv["selectborderwidth"])
self.cnv.bind('<Configure>', self._configureEvt)
# self.cnv.tag_bind('star', '<Enter>', self._enterStar)
# self.cnv.tag_bind('star', '<Leave>', self._leaveStar)
self.cnv.bind('<Motion>', self._enterStar)
self.cnv.bind('<Leave>', self._leaveStar)
# the following prevents the display from blanking
# when the button is pressed once (I tried trapping and
# discarding <Button>, as a faster solutionn, but it didn't work)
self.cnv.bind('<Button>', self._enterStar)
self.cnv.bind('<Double-Button-1>', self._setPotential)
self.center = [None,None]
self.size = [None,None]
self.azAltRad = None
self.azAltScale = None
self.sizeDeg = [180.0, 180.0]
# various dictionaries whose keys are catalog name
# note: if a catalog is deleted, it is removed from catDict
# and catPixPosObjDict, but not necessarily the others
self.catDict = {} # key=catalog name, value = catalog
self.catRedrawTimerDict = {} # key=catalog name, value = tk after id
self.catColorDict = {} # key=catalog name, value = color
self.catPixPosObjDict = {} # key=catalog name, value = list of (pix pos, obj) pairs
self.catSRDict = {} # key=catalog name, value = scriptrunner script to redisplay catalog
self.telCurrent = None
self.telTarget = None
self.telPotential = None
self.azWrapGauge = RO.CanvasUtil.Spiral (
cnv = self.cnv,
xctr = 1, yctr = 1,
begRad = 0, endRad = 0, # not yet ready to draw; canvas size unknown
angScale = -1.0,
angOff = -90.0,
)
self._setSize()
# set up automatic update of current and target telescope position
self.tccModel.axePos.addCallback(self.setTelCurrent)
self.tccModel.tccPos.addCallback(self.setTelTarget)
self.tccModel.azLim.addCallback(self.setAzLim)
self.userModel.potentialTarget.addCallback(self.setTelPotential)
self.userModel.userCatDict.addCallback(self._updUserCatDict)
def _configureEvt(self, event=None):
"""Handle the <Configure> event.
"""
self._setSize()
self.redraw()
def _setPotential(self, event):
#.........这里部分代码省略.........
示例15: __init__
def __init__(self,
master,
timeRange = 3600,
numSubplots = 1,
width = 8,
height = 2,
showGrid = True,
dateFormat = "%H:%M:%S",
updateInterval = None,
cnvTimeFunc = None,
):
"""Construct a StripChartWdg with the specified time range
Inputs:
- master: Tk parent widget
- timeRange: range of time displayed (seconds)
- width: width of graph in inches
- height: height of graph in inches
- numSubplots: the number of subplots
- showGrid: if True a grid is shown
- dateFormat: format for major axis labels, using time.strftime format
- updateInterval: now often the time axis is updated (seconds); if None a value is calculated
- cnvTimeFunc: a function that takes a POSIX timestamp (e.g. time.time()) and returns matplotlib days;
typically an instance of TimeConverter; defaults to TimeConverter(useUTC=False)
"""
tkinter.Frame.__init__(self, master)
self._timeRange = timeRange
self._isVisible = self.winfo_ismapped()
self._isFirst = True
if updateInterval is None:
updateInterval = max(0.1, min(5.0, timeRange / 2000.0))
self.updateInterval = float(updateInterval)
# print "updateInterval=", self.updateInterval
if cnvTimeFunc is None:
cnvTimeFunc = TimeConverter(useUTC=False)
self._cnvTimeFunc = cnvTimeFunc
# how many time axis updates occur before purging old data
self._maxPurgeCounter = max(1, int(0.5 + (5.0 / self.updateInterval)))
self._purgeCounter = 0
self.figure = matplotlib.figure.Figure(figsize=(width, height), frameon=True)
self.canvas = FigureCanvasTkAgg(self.figure, self)
self.canvas.get_tk_widget().grid(row=0, column=0, sticky="news")
self.canvas.mpl_connect('draw_event', self._handleDrawEvent)
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
bottomSubplot = self.figure.add_subplot(numSubplots, 1, numSubplots)
self.subplotArr = [self.figure.add_subplot(numSubplots, 1, n+1, sharex=bottomSubplot) \
for n in range(numSubplots-1)] + [bottomSubplot]
if showGrid:
for subplot in self.subplotArr:
subplot.grid(True)
self.xaxis = bottomSubplot.xaxis
bottomSubplot.xaxis_date()
self.xaxis.set_major_formatter(matplotlib.dates.DateFormatter(dateFormat))
# dictionary of constant line name: (matplotlib Line2D, matplotlib Subplot)
self._constLineDict = dict()
for subplot in self.subplotArr:
subplot._scwLines = [] # a list of contained _Line objects;
# different than the standard lines property in that:
# - lines contains Line2D objects
# - lines contains constant lines as well as data lines
subplot._scwBackground = None # background for animation
subplot.label_outer() # disable axis labels on all but the bottom subplot
subplot.set_ylim(auto=True) # set auto scaling for the y axis
self.bind("<Map>", self._handleMap)
self.bind("<Unmap>", self._handleUnmap)
self._timeAxisTimer = Timer()
self._updateTimeAxis()