当前位置: 首页>>代码示例>>Python>>正文


Python BooleanVar.get方法代码示例

本文整理汇总了Python中Tkinter.BooleanVar.get方法的典型用法代码示例。如果您正苦于以下问题:Python BooleanVar.get方法的具体用法?Python BooleanVar.get怎么用?Python BooleanVar.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Tkinter.BooleanVar的用法示例。


在下文中一共展示了BooleanVar.get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_invalid_value_domain

# 需要导入模块: from Tkinter import BooleanVar [as 别名]
# 或者: from Tkinter.BooleanVar import get [as 别名]
 def test_invalid_value_domain(self):
     v = BooleanVar(self.root, name="name")
     self.root.globalsetvar("name", "value")
     with self.assertRaises(TclError):
         v.get()
     self.root.globalsetvar("name", "1.0")
     with self.assertRaises(TclError):
         v.get()
开发者ID:0xcc,项目名称:pyston,代码行数:10,代码来源:test_variables.py

示例2: test_invalid_value_domain

# 需要导入模块: from Tkinter import BooleanVar [as 别名]
# 或者: from Tkinter.BooleanVar import get [as 别名]
 def test_invalid_value_domain(self):
     false = 0 if self.root.wantobjects() else "0"
     v = BooleanVar(self.root, name="name")
     with self.assertRaises(TclError):
         v.set("value")
     self.assertEqual(self.root.globalgetvar("name"), false)
     self.root.globalsetvar("name", "value")
     with self.assertRaises(TclError):
         v.get()
     self.root.globalsetvar("name", "1.0")
     with self.assertRaises(TclError):
         v.get()
开发者ID:1187,项目名称:PokemonGo-DesktopMap,代码行数:14,代码来源:test_variables.py

示例3: Example

# 需要导入模块: from Tkinter import BooleanVar [as 别名]
# 或者: from Tkinter.BooleanVar import get [as 别名]
class Example(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent
        
        self.initUI()
        
        
    def initUI(self):
      
        self.parent.title("Checkbutton")

        self.pack(fill=BOTH, expand=True)
        
        self.var = BooleanVar()
        
        cb = Checkbutton(self, text="Show title",
            variable=self.var, command=self.onClick)
        cb.select()
        cb.place(x=50, y=30)
        

    def onClick(self):
       
        if self.var.get() == True:
            self.master.title("Checkbutton")
        else:
            self.master.title("")
开发者ID:spiderOO7,项目名称:my_python_codes,代码行数:32,代码来源:checkbutton.py

示例4: MenuItem

# 需要导入模块: from Tkinter import BooleanVar [as 别名]
# 或者: from Tkinter.BooleanVar import get [as 别名]
class MenuItem(object):
    def __init__(self, menu, title, **kwargs):
        self._menu = menu
        if kwargs.get('checkbox'):
            # Checkbox menu item
            self._checkvar = BooleanVar()
            self._checkvar.set(kwargs.get('checked', False))

            self._menu._ctrl.add_checkbutton(label=title, command=self._on_check, variable=self._checkvar)
        else:
            # NOTE: For whatever reason, lambdas do not work in this case...
            self._menu._ctrl.add_command(label=title, command=self._on_click)

        if kwargs.get('on_click'):
            self.on_click = kwargs['on_click']

    def _on_check(self):
        """Handler for keeping on_click virtual with checkbox option"""
        self.on_click(self._checkvar.get())

    def _on_click(self):
        """Handler for keeping on_click virtual"""
        self.on_click()

    def on_click(self):
        pass

    def __exit__(self, *args):
        pass

    def __enter__(self, *args):
        return self
开发者ID:todd-x86,项目名称:tkplus,代码行数:34,代码来源:menu.py

示例5: MeasureFrame

# 需要导入模块: from Tkinter import BooleanVar [as 别名]
# 或者: from Tkinter.BooleanVar import get [as 别名]
class MeasureFrame(LabelFrame):
    def __init__(self, master, tracker, text="Measuring", *args, **kwargs):
        LabelFrame.__init__(self, master, text=text, *args, **kwargs)
        self.tracker = tracker

        self.config_frame = NamedEntryFrame(self, (OBS_INTERVAL,
                                                   NUM_SAMPLES,
                                                   NUM_OBSS),
                                            parsers={OBS_INTERVAL: float,
                                                     NUM_SAMPLES: int,
                                                     NUM_OBSS: int})
        self.config_frame.grid()

        self.save_frame = LabelFrame(self, text="Saving")
        self.dest_selector = FileSelectionFrame(self.save_frame,
                                                ask_mode="save")
        self.dest_selector.grid(row=0, column=0, columnspan=2)
        self.save_button = Button(self.save_frame, text="Save",
                                  command=bg_caller(self.save))
        self.save_button.grid(row=1, column=0)
        self.appending_var = BooleanVar()
        self.append_checkbutton = Checkbutton(self.save_frame, text="Append",
                                              variable=self.appending_var)
        self.append_checkbutton.grid(row=1, column=1)
        self.save_frame.grid()

    def measure(self, only_accurate=True):
        try:
            interval = self.config_frame.get(OBS_INTERVAL)
            samples = self.config_frame.get(NUM_SAMPLES)
            num_obss = self.config_frame.get(NUM_OBSS)
        except ValueError:
            logger.error("Could not parse input fields.")
        data = self.tracker.measure(observation_interval=interval,
                                    samples_per_observation=samples,
                                    number_of_observations=num_obss)
        if only_accurate:
            accurate_data = [point for point in data
                             if point.status == point.DATA_ACCURATE]
            num_invalid = len(data) - len(accurate_data)
            if num_invalid > 0:
                logger.warning("Hiding {} inaccurate data points."
                               .format(num_invalid))
            return accurate_data
        else:
            return data

    def save(self, only_accurate=True):
        dest = self.dest_selector.path_var.get()
        if not dest:
            logger.error("Must select a destination file.")
            return

        data = self.measure(only_accurate=only_accurate)
        w = csv.writer(open(dest, 'a' if self.appending_var.get() else 'w'))
        for point in data:
            w.writerow((point.time, point.position.r,
                        point.position.theta, point.position.phi))

        logger.info("Saved measurements into {!r}".format(dest))
开发者ID:speezepearson,项目名称:PyMMT,代码行数:62,代码来源:measureframe.py

示例6: test_get

# 需要导入模块: from Tkinter import BooleanVar [as 别名]
# 或者: from Tkinter.BooleanVar import get [as 别名]
 def test_get(self):
     v = BooleanVar(self.root, True, "name")
     self.assertIs(v.get(), True)
     self.root.globalsetvar("name", "0")
     self.assertIs(v.get(), False)
     self.root.globalsetvar("name", 42 if self.root.wantobjects() else 1)
     self.assertIs(v.get(), True)
     self.root.globalsetvar("name", 0)
     self.assertIs(v.get(), False)
     self.root.globalsetvar("name", 42L if self.root.wantobjects() else 1L)
     self.assertIs(v.get(), True)
     self.root.globalsetvar("name", 0L)
     self.assertIs(v.get(), False)
     self.root.globalsetvar("name", "on")
     self.assertIs(v.get(), True)
     self.root.globalsetvar("name", u"0")
     self.assertIs(v.get(), False)
     self.root.globalsetvar("name", u"on")
     self.assertIs(v.get(), True)
开发者ID:1187,项目名称:PokemonGo-DesktopMap,代码行数:21,代码来源:test_variables.py

示例7: Example

# 需要导入模块: from Tkinter import BooleanVar [as 别名]
# 或者: from Tkinter.BooleanVar import get [as 别名]

#.........这里部分代码省略.........
		self.noise.set("0.75")
		e3 = Entry(self, width=12, textvariable=self.noise)
		e3.grid(row=4,column=3, sticky=W, pady=5, padx=5)
		e3_label = Label(self, text="Noise (LSB)")
		e3_label.grid(row=4,column=2, sticky=E, pady=5, padx=5)
		
		self.n_sigma.set("4")
		e4 = Entry(self, width=12, textvariable=self.n_sigma)
		e4.grid(row=4,column=5, sticky=W, pady=5, padx=5)
		e4_label = Label(self, text="Noise Threshold")
		e4_label.grid(row=4,column=4, sticky=E, pady=5, padx=5)

		self.thr1.set("3")
		e5 = Entry(self, width=12, textvariable=self.thr1)
		e5.grid(row=5,column=1, sticky=W, pady=5, padx=5)
		e5_label = Label(self, text="Threshold 1")
		e5_label.grid(row=5,column=0, sticky=E, pady=5, padx=5)

		self.thr2.set("5")
		e6 = Entry(self, width=12, textvariable=self.thr2)
		e6.grid(row=5,column=3, sticky=W, pady=5, padx=5)
		e6_label = Label(self, text="Threshold 2")
		e6_label.grid(row=5,column=2, sticky=E, pady=5, padx=5)

		self.thr3.set("1")
		e7 = Entry(self, width=12, textvariable=self.thr3)
		e7.grid(row=5,column=5, sticky=W, pady=5, padx=5)
		e7_label = Label(self, text="Threshold 3")
		e7_label.grid(row=5,column=4, sticky=E, pady=5, padx=5)





		# Main buttons
		obtn = Button(self, text="GO!!", command=self.DBLR_f)
		obtn.grid(row=6, column=4, sticky=E, pady=10)

		cbtn = Button(self, text="Quit", command=self.quit)
		cbtn.grid(row=6, column=5, sticky=E, pady=10)

		hbtn = Button(self, text="Help", command=self.help_f)
		hbtn.grid(row=6, column=0, sticky=W, pady=10)
		

	def help_f(self):
		top = Toplevel()
		top.title("HELP")
		msg = Message(top, width= 500, 
                 text="Noise Threshold (NT) - Noise Based Main Threshold \
(Sigmas)\n Threshold 1 - Main Threshold (LSBs) \n Threshold 2 - End of Pulse Error \n \
Threshold 3 - End of Tail Error \n When Thr1 = Thr3 = 0 their values are defined as: \n \
(THR1 = NT (LSBs) / THR3 = NT*NOISE_ADC / 5)") 
		msg.pack()

		button = Button(top, text="Close", command=top.destroy)
		button.pack()
#		tkMessageBox.showinfo("HELP", "Noise Threshold (NT) - Noise Based Main Threshold (Sigmas)\
#Threshold 1 - Main Threshold (LSBs)\
#Threshold 2 - End of Pulse Error\
#Threshold 3 - End of Tail Error\
#When Thr1 = Thr3 = 0 their values are defined as:\
#(THR1 = NT (LSBs) / THR3 = NT*NOISE_ADC/5)")


	def DBLR_f(self):
		
		global a
		
		if (self.graph_sw.get()==True): 
			b=a
			a=a+1
		else: 
			b=0		
		
		aux=self.base_path.get()
		path=''.join([aux,str(self.meas.get()),'.txt'])
		g=pd.read_csv(path)
		f=4096-g.values

		recons,energia = DB.BLR( signal_daq=f.flatten().astype(float),
						  coef=self.coef.get(),
						  n_sigma=self.n_sigma.get(),
						  NOISE_ADC=self.noise.get(),
						  thr1=self.thr1.get(),
						  thr2=self.thr2.get(),
						  thr3=self.thr3.get(),
						  plot=False)
		plt.figure(a)						
		plt.plot(recons)
		plt.figtext(0.2,0.75, ('ENERGY = %0.2f ' % (energia)))
		plt.show(block=False)
				

	def centerUI(self,w,h):
		sw = self.parent.winfo_screenwidth()
		sh = self.parent.winfo_screenheight()
		x  = (sw-w)/2
		y  = (sh-h)/2
		self.parent.geometry('%dx%d+%d+%d' % (w,h,x,y))
开发者ID:jjgomezcadenas,项目名称:DBLR,代码行数:104,代码来源:DBLR_GUI.py

示例8: Cap

# 需要导入模块: from Tkinter import BooleanVar [as 别名]
# 或者: from Tkinter.BooleanVar import get [as 别名]
class Cap(Frame):
	def __init__(self):
		' set defaults, create widgets, bind callbacks, start live view '
		self.root = Tk()
		# menu:
		self.menu = Menu(self.root)
		self.root.config(menu=self.menu)
		# bind global keypresses:
		self.root.bind('q', lambda e: self.root.quit())
		self.root.bind('x', lambda e: self.root.quit())
		self.root.bind('<Destroy>', self.do_stop_video)
		self.root.bind('<space>', self.do_single_shot)
		self.root.bind('<Return>', self.do_single_shot)
		self.root.bind('<Button-3>', self.do_single_shot)
		self.root.bind('<Left>', lambda e: self.degree.set(-90))
		self.root.bind('<Right>', lambda e: self.degree.set(90))
		self.root.bind('<Up>', lambda e: self.degree.set(0))
		self.root.bind('a', lambda e: self.autocontrast.set(not self.autocontrast.get()))
		self.root.bind('e', lambda e: self.equalize.set(not self.equalize.get()))
		self.root.bind('g', lambda e: self.grayscale.set(not self.grayscale.get()))
		self.root.bind('i', lambda e: self.invert.set(not self.invert.get()))
		self.root.bind('s', lambda e: self.solarize.set(not self.solarize.get()))
		# config:
		self.config = RawConfigParser()
		self.config.read('filmroller.conf')
		if not self.config.has_section('global'):
			self.config.add_section('global')
		self.video = None
		self.invert = BooleanVar(name='invert')
		self.invert.set(self.config_get('invert', True))
		self.invert.trace('w', self.do_configure)
		self.grayscale = BooleanVar(name='grayscale')
		self.grayscale.set(self.config_get('grayscale', False))
		self.grayscale.trace('w', self.do_configure)
		self.autocontrast = BooleanVar(name='autocontrast')
		self.autocontrast.set(self.config_get('autocontrast', True))
		self.autocontrast.trace('w', self.do_configure)
		self.equalize = BooleanVar(name='equalize')
		self.equalize.set(self.config_get('equalize', False))
		self.equalize.trace('w', self.do_configure)
		self.solarize = BooleanVar(name='solarize')
		self.solarize.set(self.config_get('solarize', False))
		self.solarize.trace('w', self.do_configure)
		self.degree = IntVar(name='degree')
		self.degree.set(0)
		self.filename = StringVar(name='filename')
		self.videodevice = StringVar(name='videodevice')
		dev_names = sorted(['/dev/{}'.format(x) for x in listdir('/dev') if x.startswith('video')])
		d = self.config_get('videodevice', dev_names[-1])
		if not d in dev_names:
			d = dev_names[-1]
		self.videodevice.set(d)
		self.videodevice.trace('w', self.do_configure)
		#
		self.path = 'filmroller'
		if not exists(self.path):
			makedirs(self.path)
		# create gui:
		Frame.__init__(self, self.root)
		self.grid()
		self.x_canvas = Canvas(self, width=640, height=640, )
		self.x_canvas.pack(side='top')
		self.x_canvas.bind('<Button-1>', self.do_change_rotation)
		Checkbutton(self, text='Invert', variable=self.invert).pack(side='left')
		Checkbutton(self, text='Gray', variable=self.grayscale).pack(side='left')
		Checkbutton(self, text='Auto', variable=self.autocontrast).pack(side='left')
		OptionMenu(self, self.videodevice, *dev_names, command=self.restart_video).pack(side='left')
		Button(self, text='First role', command=self.do_first_role).pack(side='left')
		Label(self, textvariable=self.filename).pack(side='left')
		Button(self, text='Next role', command=self.do_inc_role).pack(side='left')
		Button(self, text='Take!', command=self.do_single_shot).pack(side='right')
		#filemenu = Menu(self.menu)
		#self.menu.add_cascade(label=self.videodevice.get(), menu=filemenu, )
		#for n in dev_names:
		#	filemenu.add_command(label=n, )
		#filemenu.add_separator()
		# start operation:
		self.do_first_role()
		self.do_start_video()

	def do_change_rotation(self, event):
		' determine where the image was clicked and turn that to the top '
		if event.x < 200:
			self.degree.set(-90)
		elif event.x > 640 - 200:
			self.degree.set(90)
		else:
			self.degree.set(0)

	def config_get(self, name, default):
		' read a configuration entry, fallback to default if not already stored '
		if not self.config.has_option('global', name):
			return default
		if isinstance(default, bool):
			return self.config.getboolean('global', name)
		else:
			return self.config.get('global', name)

	def do_configure(self, name, mode, cbname):
		' change a configuration entry '
#.........这里部分代码省略.........
开发者ID:JimmyDurandWesolowski,项目名称:python-v4l2capture,代码行数:103,代码来源:filmroller.py

示例9: __init__

# 需要导入模块: from Tkinter import BooleanVar [as 别名]
# 或者: from Tkinter.BooleanVar import get [as 别名]
class SearchEngine:
    """Handles searching a text widget for Find, Replace, and Grep."""

    def __init__(self, root):
        '''Initialize Variables that save search state.

        The dialogs bind these to the UI elements present in the dialogs.
        '''
        self.root = root  # need for report_error()
        self.patvar = StringVar(root, '')   # search pattern
        self.revar = BooleanVar(root, False)   # regular expression?
        self.casevar = BooleanVar(root, False)   # match case?
        self.wordvar = BooleanVar(root, False)   # match whole word?
        self.wrapvar = BooleanVar(root, True)   # wrap around buffer?
        self.backvar = BooleanVar(root, False)   # search backwards?

    # Access methods

    def getpat(self):
        return self.patvar.get()

    def setpat(self, pat):
        self.patvar.set(pat)

    def isre(self):
        return self.revar.get()

    def iscase(self):
        return self.casevar.get()

    def isword(self):
        return self.wordvar.get()

    def iswrap(self):
        return self.wrapvar.get()

    def isback(self):
        return self.backvar.get()

    # Higher level access methods

    def setcookedpat(self, pat):
        "Set pattern after escaping if re."
        # called only in SearchDialog.py: 66
        if self.isre():
            pat = re.escape(pat)
        self.setpat(pat)

    def getcookedpat(self):
        pat = self.getpat()
        if not self.isre():  # if True, see setcookedpat
            pat = re.escape(pat)
        if self.isword():
            pat = r"\b%s\b" % pat
        return pat

    def getprog(self):
        "Return compiled cooked search pattern."
        pat = self.getpat()
        if not pat:
            self.report_error(pat, "Empty regular expression")
            return None
        pat = self.getcookedpat()
        flags = 0
        if not self.iscase():
            flags = flags | re.IGNORECASE
        try:
            prog = re.compile(pat, flags)
        except re.error as what:
            args = what.args
            msg = args[0]
            col = arg[1] if len(args) >= 2 else -1
            self.report_error(pat, msg, col)
            return None
        return prog

    def report_error(self, pat, msg, col=-1):
        # Derived class could override this with something fancier
        msg = "Error: " + str(msg)
        if pat:
            msg = msg + "\nPattern: " + str(pat)
        if col >= 0:
            msg = msg + "\nOffset: " + str(col)
        tkMessageBox.showerror("Regular expression error",
                               msg, master=self.root)

    def search_text(self, text, prog=None, ok=0):
        '''Return (lineno, matchobj) or None for forward/backward search.

        This function calls the right function with the right arguments.
        It directly return the result of that call.

        Text is a text widget. Prog is a precompiled pattern.
        The ok parameteris a bit complicated as it has two effects.

        If there is a selection, the search begin at either end,
        depending on the direction setting and ok, with ok meaning that
        the search starts with the selection. Otherwise, search begins
        at the insert mark.

#.........这里部分代码省略.........
开发者ID:van7hu,项目名称:fanca,代码行数:103,代码来源:SearchEngine.py

示例10: GrepDialog

# 需要导入模块: from Tkinter import BooleanVar [as 别名]
# 或者: from Tkinter.BooleanVar import get [as 别名]
class GrepDialog(SearchDialogBase):

    title = "Find in Files Dialog"
    icon = "Grep"
    needwrapbutton = 0

    def __init__(self, root, engine, flist):
        SearchDialogBase.__init__(self, root, engine)
        self.flist = flist
        self.globvar = StringVar(root)
        self.recvar = BooleanVar(root)

    def open(self, text, searchphrase, io=None):
        SearchDialogBase.open(self, text, searchphrase)
        if io:
            path = io.filename or ""
        else:
            path = ""
        dir, base = os.path.split(path)
        head, tail = os.path.splitext(base)
        if not tail:
            tail = ".py"
        self.globvar.set(os.path.join(dir, "*" + tail))

    def create_entries(self):
        SearchDialogBase.create_entries(self)
        self.globent = self.make_entry("In files:", self.globvar)[0]

    def create_other_buttons(self):
        f = self.make_frame()[0]

        btn = Checkbutton(f, anchor="w",
                variable=self.recvar,
                text="Recurse down subdirectories")
        btn.pack(side="top", fill="both")
        btn.select()

    def create_command_buttons(self):
        SearchDialogBase.create_command_buttons(self)
        self.make_button("Search Files", self.default_command, 1)

    def default_command(self, event=None):
        prog = self.engine.getprog()
        if not prog:
            return
        path = self.globvar.get()
        if not path:
            self.top.bell()
            return
        from idlelib.OutputWindow import OutputWindow  # leave here!
        save = sys.stdout
        try:
            sys.stdout = OutputWindow(self.flist)
            self.grep_it(prog, path)
        finally:
            sys.stdout = save

    def grep_it(self, prog, path):
        dir, base = os.path.split(path)
        list = self.findfiles(dir, base, self.recvar.get())
        list.sort()
        self.close()
        pat = self.engine.getpat()
        print("Searching %r in %s ..." % (pat, path))
        hits = 0
        try:
            for fn in list:
                try:
                    with open(fn) as f:
                        for lineno, line in enumerate(f, 1):
                            if line[-1:] == '\n':
                                line = line[:-1]
                            if prog.search(line):
                                sys.stdout.write("%s: %s: %s\n" %
                                                 (fn, lineno, line))
                                hits += 1
                except IOError as msg:
                    print(msg)
            print(("Hits found: %s\n"
                  "(Hint: right-click to open locations.)"
                  % hits) if hits else "No hits.")
        except AttributeError:
            # Tk window has been closed, OutputWindow.text = None,
            # so in OW.write, OW.text.insert fails.
            pass

    def findfiles(self, dir, base, rec):
        try:
            names = os.listdir(dir or os.curdir)
        except os.error as msg:
            print(msg)
            return []
        list = []
        subdirs = []
        for name in names:
            fn = os.path.join(dir, name)
            if os.path.isdir(fn):
                subdirs.append(fn)
            else:
                if fnmatch.fnmatch(name, base):
#.........这里部分代码省略.........
开发者ID:Darriall,项目名称:pypy,代码行数:103,代码来源:GrepDialog.py

示例11: test_get

# 需要导入模块: from Tkinter import BooleanVar [as 别名]
# 或者: from Tkinter.BooleanVar import get [as 别名]
 def test_get(self):
     v = BooleanVar(self.root, True, 'name')
     self.assertAlmostEqual(True, v.get())
     self.root.globalsetvar('name', '0')
     self.assertAlmostEqual(False, v.get())
开发者ID:aevitas,项目名称:wotsdk,代码行数:7,代码来源:test_tkintertest_variables.py

示例12: __init__

# 需要导入模块: from Tkinter import BooleanVar [as 别名]
# 或者: from Tkinter.BooleanVar import get [as 别名]
class SearchEngine:
    """Handles searching a text widget for Find, Replace, and Grep."""

    def __init__(self, root):
        """Initialize Variables that save search state.
        
        The dialogs bind these to the UI elements present in the dialogs.
        """
        self.root = root
        self.patvar = StringVar(root, '')
        self.revar = BooleanVar(root, False)
        self.casevar = BooleanVar(root, False)
        self.wordvar = BooleanVar(root, False)
        self.wrapvar = BooleanVar(root, True)
        self.backvar = BooleanVar(root, False)

    def getpat(self):
        return self.patvar.get()

    def setpat(self, pat):
        self.patvar.set(pat)

    def isre(self):
        return self.revar.get()

    def iscase(self):
        return self.casevar.get()

    def isword(self):
        return self.wordvar.get()

    def iswrap(self):
        return self.wrapvar.get()

    def isback(self):
        return self.backvar.get()

    def setcookedpat(self, pat):
        """Set pattern after escaping if re."""
        if self.isre():
            pat = re.escape(pat)
        self.setpat(pat)

    def getcookedpat(self):
        pat = self.getpat()
        if not self.isre():
            pat = re.escape(pat)
        if self.isword():
            pat = '\\b%s\\b' % pat
        return pat

    def getprog(self):
        """Return compiled cooked search pattern."""
        pat = self.getpat()
        if not pat:
            self.report_error(pat, 'Empty regular expression')
            return None
        else:
            pat = self.getcookedpat()
            flags = 0
            if not self.iscase():
                flags = flags | re.IGNORECASE
            try:
                prog = re.compile(pat, flags)
            except re.error as what:
                args = what.args
                msg = args[0]
                col = arg[1] if len(args) >= 2 else -1
                self.report_error(pat, msg, col)
                return None

            return prog

    def report_error(self, pat, msg, col = -1):
        msg = 'Error: ' + str(msg)
        if pat:
            msg = msg + '\nPattern: ' + str(pat)
        if col >= 0:
            msg = msg + '\nOffset: ' + str(col)
        tkMessageBox.showerror('Regular expression error', msg, master=self.root)

    def search_text(self, text, prog = None, ok = 0):
        """Return (lineno, matchobj) or None for forward/backward search.
        
        This function calls the right function with the right arguments.
        It directly return the result of that call.
        
        Text is a text widget. Prog is a precompiled pattern.
        The ok parameteris a bit complicated as it has two effects.
        
        If there is a selection, the search begin at either end,
        depending on the direction setting and ok, with ok meaning that
        the search starts with the selection. Otherwise, search begins
        at the insert mark.
        
        To aid progress, the search functions do not return an empty
        match at the starting position unless ok is True.
        """
        if not prog:
            prog = self.getprog()
#.........这里部分代码省略.........
开发者ID:webiumsk,项目名称:WOT-0.9.15.1,代码行数:103,代码来源:searchengine.py

示例13: App

# 需要导入模块: from Tkinter import BooleanVar [as 别名]
# 或者: from Tkinter.BooleanVar import get [as 别名]
class App(Frame):
    def __init__(self, master=None):
        self.master = master
        Frame.__init__(self, master, relief=SUNKEN, bd=2)

        self.gcode = []
        self.slicing = False
        self.printing = False
        self.connected = False
        self.monitorTemp = False
        self.paused = False
        self.sdpresent = False
        self.sdlisting = False
        self.sdchecking = False
        self.sdprinting = False
        self.sdpaused = False
        self.sduploading = False
        self.sdbytes = 0
        self.sdmaxbytes = 0
        self.insidelisting = False
        self.readingFirmware = False
        self.sdfiles = []
        self.bedtemp = float(0)
        self.bedtarget = float(0)
        self.exttemp = float(0)
        self.exttarget = float(0)
        self.acceleration = 0
        self.m114count = 0
        self.speedcount = 0
        self.location = [0, 0, 0, 0]
        self.pausePoint = [0, 0, 0, 0]
        self.percent = 0.0
        self.ets = "??"
        self.gcodeInfo = None
        self.GCodeFile = None
        self.StlFile = None
        self.Profile = None
        self.printStartLine = 0
        self.startTime = 0
        self.endTime = 0
        self.elapsedTime = 0
        self.FanSpeed = 0
        self.FeedMultiply = 100
        self.ExtrudeMultiply = 100

        self.timingReport = None
        self.filamentReport = None
        self.measurementsReport = None

        self.macroButtons = None

        self.rpt1re = re.compile(" *T:([0-9\.]+) *E:[0-9\.]+ *B:([0-9\.]+)")
        self.rpt2re = re.compile(" *T:([0-9\.]+) *E:[0-9\.]+ *W:.*")
        self.locrptre = re.compile("^X:([0-9\.\-]+)Y:([0-9\.\-]+)Z:([0-9\.\-]+)E:([0-9\.\-]+) *Count")
        self.speedrptre = re.compile("Fan speed:([0-9]+) Feed Multiply:([0-9]+) Extrude Multiply:([0-9]+)")

        self.sdre = re.compile("SD printing byte *([0-9]+) *\/ *([0-9]+)")

        self.printer = printcore()
        self.settings = Settings()
        self.settings.cmdFolder = cmd_folder
        self.logger = Logger(self)

        if self.settings.speedcommand is not None:
            allow_while_printing.append(self.settings.speedcommand)

        self.acceleration = self.settings.acceleration

        self.dataLoggers = {}
        for d in DLLIST:
            self.dataLoggers[d] = DataLogger(self, d)

        self.skeinforge = Skeinforge(self.settings)
        self.slic3r = Slic3r(self.settings)

        self.httpServer = RepRapServer(self, self.printer, self.settings, self.logger, self.settings.port)

        self.menubar = Menu(self)
        self.filemenu = Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label="File", menu=self.filemenu)
        self.filemenu.add_command(label="Slice", command=self.openSTLFile)
        self.filemenu.add_command(label="Load GCode", command=self.openGCodeFile)
        self.slicemenuindex = self.filemenu.index("Slice")
        self.loadgcodemenuindex = self.filemenu.index("Load GCode")

        self.filemenu.add_separator()
        self.filemenu.add_command(label="Exit", command=self.quitApp)

        self.editmenu = Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label="Edit", menu=self.editmenu)

        self.editmenu.add_command(label="Settings", command=self.editSettings)
        self.editmenu.add_command(label="Firmware Settings", command=self.FirmwareSettings)
        self.editmenu.add_separator()
        self.editmenu.add_command(label=GCODE_MENU_TEXT, command=self.doGEdit, state=DISABLED)

        self.slicermenu = Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label="Slicer", menu=self.slicermenu)
        self.rbSlicer = StringVar()

#.........这里部分代码省略.........
开发者ID:jbernardis,项目名称:repraphost,代码行数:103,代码来源:repraphost.py

示例14: GrepDialog

# 需要导入模块: from Tkinter import BooleanVar [as 别名]
# 或者: from Tkinter.BooleanVar import get [as 别名]
class GrepDialog(SearchDialogBase):
    title = "Find in Files Dialog"
    icon = "Grep"
    needwrapbutton = 0
    bottom_btns = [("Search Files", 'default_command', 1)]

    def __init__(self, root, engine, flist):
        SearchDialogBase.__init__(self, root, engine)
        self.flist = flist
        self.globvar = StringVar(root)
        self.recvar = BooleanVar(root)

    def open(self, text, searchphrase, io=None):
        SearchDialogBase.open(self, text, searchphrase)
        if io:
            path = io.filename or ""
        else:
            path = ""
        dir, base = os.path.split(path)
        head, tail = os.path.splitext(base)
        if not tail:
            tail = ".py"
        self.globvar.set(os.path.join(dir, "*" + tail))

    def create_entries(self):
        SearchDialogBase.create_entries(self)
        self.globent = self.make_entry("In files", self.globvar)

    def create_other_buttons(self):
        f = self.make_frame()

        btn = Checkbutton(f, variable=self.recvar,
                text="Recurse down subdirectories")
        btn.pack(side="top", fill="both")
        btn.invoke()

    def create_command_buttons(self):
        SearchDialogBase.create_command_buttons(self)

    def default_command(self, event=None):
        prog = self.engine.getprog()
        if not prog:
            return
        path = self.globvar.get()
        if not path:
            self.top.bell()
            return
        from OutputWindow import OutputWindow
        save = sys.stdout
        try:
            sys.stdout = OutputWindow(self.flist)
            self.grep_it(prog, path)
        finally:
            sys.stdout = save

    def grep_it(self, prog, path):
        dir, base = os.path.split(path)
        list = self.findfiles(dir, base, self.recvar.get())
        list.sort()
        self.close()
        pat = self.engine.getpat()
        print "Searching %r in %s ..." % (pat, path)
        hits = 0
        for fn in list:
            try:
                f = open(fn)
            except IOError, msg:
                print msg
                continue
            lineno = 0
            while 1:
                block = f.readlines(100000)
                if not block:
                    break
                for line in block:
                    lineno = lineno + 1
                    if line[-1:] == '\n':
                        line = line[:-1]
                    if prog.search(line):
                        sys.stdout.write("%s: %s: %s\n" % (fn, lineno, line))
                        hits = hits + 1
        if hits:
            if hits == 1:
                s = ""
            else:
                s = "s"
            print "Found", hits, "hit%s." % s
            print "(Hint: right-click to open locations.)"
        else:
            print "No hits."
开发者ID:8848,项目名称:Pymol-script-repo,代码行数:92,代码来源:GrepDialog.py

示例15: FontChooser

# 需要导入模块: from Tkinter import BooleanVar [as 别名]
# 或者: from Tkinter.BooleanVar import get [as 别名]
class FontChooser( tkSimpleDialog.Dialog ):
    BASIC = 1
    ALL   = 2

    def __init__( self, parent, defaultfont=None, showstyles=None ):
        self._family       = StringVar(  value='Century Schoolbook L')
        self._sizeString   = StringVar(  value='20'          )
        self._weight       = StringVar(  value=tkFont.NORMAL )
        self._slant        = StringVar(  value=tkFont.ROMAN  )
        self._isUnderline  = BooleanVar( value=False         )
        self._isOverstrike = BooleanVar( value=False         )
        if defaultfont:
            self._initialize( defaultfont )

        self._currentFont  = tkFont.Font( font=self.getFontTuple() )

        self._showStyles   = showstyles

        self.sampleText      = None

        tkSimpleDialog.Dialog.__init__( self, parent, 'Font Chooser' )

    def _initialize( self, aFont ):
        if not isinstance( aFont, tkFont.Font ):
            aFont = tkFont.Font( font=aFont )

        fontOpts = aFont.actual( )

        self._family.set(       fontOpts[ 'family'     ] )
        self._sizeString.set(   fontOpts[ 'size'       ] )
        self._weight.set(       fontOpts[ 'weight'     ] )
        self._slant.set(        fontOpts[ 'slant'      ] )
        self._isUnderline.set(  fontOpts[ 'underline'  ] )
        self._isOverstrike.set( fontOpts[ 'overstrike' ] )

    def body( self, master ):
        theRow = 0

        Label( master, text="Font Family" ).grid( row=theRow, column=0 )
        Label( master, text="Font Size" ).grid( row=theRow, column=2 )

        theRow += 1

        # Font Families
        fontList = ttk.Combobox( master,  height=10, textvariable=self._family )
        fontList.grid( row=theRow, column=0, columnspan=2, sticky=N+S+E+W, padx=10 )
        rawfamilyList = list(tkFont.families( ))
        rawfamilyList.sort()
        # print rawfamilyList
        familyList=[]
        for family in rawfamilyList:
            if family[0] == '@':
                continue
            familyList.append(family)
        fontList.configure( values=familyList )
        fontList.bind('<<ComboboxSelected>>', self.selectionChanged)

        # Font Sizes
        sizeList = ttk.Combobox( master,  height=10, width=5, textvariable=self._sizeString )
        sizeList.grid( row=theRow, column=2, columnspan=2, sticky=N+S+E+W, padx=10 )
        sizes=[]
        for size in xrange( 10,50 ):
            sizes.append( str(size) )
        sizeList.configure( values=sizes)
        sizeList.bind('<<ComboboxSelected>>', self.selectionChanged)

        # Styles
        if self._showStyles is not None:
            theRow += 1
            if self._showStyles in ( FontChooser.ALL, FontChooser.BASIC ):
                Label( master, text='Styles', anchor=W ).grid( row=theRow, column=0, pady=10, sticky=W )

                theRow += 1

                Checkbutton( master, text="bold", command=self.selectionChanged, offvalue='normal', onvalue='bold', variable=self._weight ).grid(row=theRow, column=0)
                Checkbutton( master, text="italic", command=self.selectionChanged, offvalue='roman', onvalue='italic', variable=self._slant ).grid(row=theRow, column=1)

        if self._showStyles == FontChooser.ALL:
            Checkbutton( master, text="underline", command=self.selectionChanged, offvalue=False, onvalue=True, variable=self._isUnderline ).grid(row=theRow, column=2)
            Checkbutton( master, text="overstrike", command=self.selectionChanged, offvalue=False, onvalue=True, variable=self._isOverstrike ).grid(row=theRow, column=3)

        # Sample Text
            theRow += 1

            Label( master, text='Sample Text', anchor=W ).grid( row=theRow, column=0, pady=10, sticky=W )

            theRow += 1

            self.sampleText = Text( master, height=11, width=70 )
            self.sampleText.insert( INSERT,'ABC...XYZ\nabc....xyz', 'fontStyle' )
            self.sampleText.config( state=DISABLED )
            self.sampleText.tag_config( 'fontStyle', font=self._currentFont )
            self.sampleText.grid( row=theRow, column=0, columnspan=4, padx=10 )

    def apply( self ):
        self.result = self.getFontTuple( )

    def selectionChanged( self, something=None ):
        self._currentFont.configure( family=self._family.get(),
                                     size=self._sizeString.get(),
#.........这里部分代码省略.........
开发者ID:JosHel,项目名称:pipresents-gapless,代码行数:103,代码来源:pp_edititem.py


注:本文中的Tkinter.BooleanVar.get方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。