Python Tkinter.TclError() Examples

The following are 30 code examples of Tkinter.TclError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module Tkinter , or try the search function .
Example #1
Source File: misc.py    From SEM with MIT License 7 votes vote down vote up
def add_all(self, event):
        if self.frame.current_selection is not None:
            start = self.frame.charindex2position(self.frame.current_selection.lb)
            end = self.frame.charindex2position(self.frame.current_selection.ub)
        else:
            start, end = ("sel.first", "sel.last")
        try:
            target = re.escape(self.frame.text.get(start, end).strip())
            pattern = (u"\\b" if target[0].isalnum() else u"((?<=\\s)|(?<=^))") + target + (u"\\b" if target[-1].isalnum() else u"(?=\\s|$)")
            regex = re.compile(pattern, re.U + re.M)
            for match in regex.finditer(self.frame.doc.content):
                cur_start, cur_end = self.frame.charindex2position(match.start()), self.frame.charindex2position(match.end())
                if Tag(self.type, match.start(), match.end()) not in self.frame.current_annotations:
                    self.frame.wish_to_add = [self.type, cur_start, cur_end]
                    self.frame.add_annotation(None, remove_focus=False)
        except tkinter.TclError:
            raise
        self.frame.type_combos[self.level].current(0)
        self.frame.wish_to_add = None
        self.frame.current_selection = None
        self.frame.current_type_hierarchy_level = 0
        self.frame.update_level()
        self.frame.text.tag_remove("BOLD",  "1.0", 'end') 
Example #2
Source File: test_style.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_theme_use(self):
        self.assertRaises(Tkinter.TclError, self.style.theme_use,
            'nonexistingname')

        curr_theme = self.style.theme_use()
        new_theme = None
        for theme in self.style.theme_names():
            if theme != curr_theme:
                new_theme = theme
                self.style.theme_use(theme)
                break
        else:
            # just one theme available, can't go on with tests
            return

        self.assertFalse(curr_theme == new_theme)
        self.assertFalse(new_theme != self.style.theme_use())

        self.style.theme_use(curr_theme) 
Example #3
Source File: test_widgets.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_column(self):
        # return a dict with all options/values
        self.assertIsInstance(self.tv.column('#0'), dict)
        # return a single value of the given option
        if self.wantobjects:
            self.assertIsInstance(self.tv.column('#0', width=None), int)
        # set a new value for an option
        self.tv.column('#0', width=10)
        # testing new way to get option value
        self.assertEqual(self.tv.column('#0', 'width'),
                         10 if self.wantobjects else '10')
        self.assertEqual(self.tv.column('#0', width=None),
                         10 if self.wantobjects else '10')
        # check read-only option
        self.assertRaises(tkinter.TclError, self.tv.column, '#0', id='X')

        self.assertRaises(tkinter.TclError, self.tv.column, 'invalid')
        invalid_kws = [
            {'unknown_option': 'some value'},  {'stretch': 'wrong'},
            {'anchor': 'wrong'}, {'width': 'wrong'}, {'minwidth': 'wrong'}
        ]
        for kw in invalid_kws:
            self.assertRaises(tkinter.TclError, self.tv.column, '#0',
                **kw) 
Example #4
Source File: tkagg.py    From Computable with MIT License 6 votes vote down vote up
def blit(photoimage, aggimage, bbox=None, colormode=1):
    tk = photoimage.tk

    if bbox is not None:
        bbox_array = bbox.__array__()
    else:
        bbox_array = None
    try:
        tk.call("PyAggImagePhoto", photoimage, id(aggimage), colormode, id(bbox_array))
    except Tk.TclError:
        try:
            try:
                _tkagg.tkinit(tk.interpaddr(), 1)
            except AttributeError:
                _tkagg.tkinit(id(tk), 0)
            tk.call("PyAggImagePhoto", photoimage, id(aggimage), colormode, id(bbox_array))
        except (ImportError, AttributeError, Tk.TclError):
            raise 
Example #5
Source File: test_widgets.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_delete(self):
        self.assertRaises(tkinter.TclError, self.tv.delete, '#0')

        item_id = self.tv.insert('', 'end')
        item2 = self.tv.insert(item_id, 'end')
        self.assertEqual(self.tv.get_children(), (item_id, ))
        self.assertEqual(self.tv.get_children(item_id), (item2, ))

        self.tv.delete(item_id)
        self.assertFalse(self.tv.get_children())

        # reattach should fail
        self.assertRaises(tkinter.TclError,
            self.tv.reattach, item_id, '', 'end')

        # test multiple item delete
        item1 = self.tv.insert('', 'end')
        item2 = self.tv.insert('', 'end')
        self.assertEqual(self.tv.get_children(), (item1, item2))

        self.tv.delete(item1, item2)
        self.assertFalse(self.tv.get_children()) 
Example #6
Source File: test_widgets.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_invoke(self):
        success = []
        def cb_test():
            success.append(1)
            return "cb test called"

        cbtn = ttk.Checkbutton(command=cb_test)
        # the variable automatically created by ttk.Checkbutton is actually
        # undefined till we invoke the Checkbutton
        self.assertEqual(cbtn.state(), ('alternate', ))
        self.assertRaises(Tkinter.TclError, cbtn.tk.globalgetvar,
            cbtn['variable'])

        res = cbtn.invoke()
        self.assertEqual(res, "cb test called")
        self.assertEqual(cbtn['onvalue'],
            cbtn.tk.globalgetvar(cbtn['variable']))
        self.assertTrue(success)

        cbtn['command'] = ''
        res = cbtn.invoke()
        self.assertEqual(res, '')
        self.assertFalse(len(success) > 1)
        self.assertEqual(cbtn['offvalue'],
            cbtn.tk.globalgetvar(cbtn['variable'])) 
Example #7
Source File: test_widgets.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_sashpos(self):
        self.assertRaises(tkinter.TclError, self.paned.sashpos, None)
        self.assertRaises(tkinter.TclError, self.paned.sashpos, '')
        self.assertRaises(tkinter.TclError, self.paned.sashpos, 0)

        child = ttk.Label(self.paned, text='a')
        self.paned.add(child, weight=1)
        self.assertRaises(tkinter.TclError, self.paned.sashpos, 0)
        child2 = ttk.Label(self.paned, text='b')
        self.paned.add(child2)
        self.assertRaises(tkinter.TclError, self.paned.sashpos, 1)

        self.paned.pack(expand=True, fill='both')
        self.paned.wait_visibility()

        curr_pos = self.paned.sashpos(0)
        self.paned.sashpos(0, 1000)
        self.assertNotEqual(curr_pos, self.paned.sashpos(0))
        self.assertIsInstance(self.paned.sashpos(0), int) 
Example #8
Source File: test_widgets.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_sashpos(self):
        self.assertRaises(Tkinter.TclError, self.paned.sashpos, None)
        self.assertRaises(Tkinter.TclError, self.paned.sashpos, '')
        self.assertRaises(Tkinter.TclError, self.paned.sashpos, 0)

        child = ttk.Label(self.paned, text='a')
        self.paned.add(child, weight=1)
        self.assertRaises(Tkinter.TclError, self.paned.sashpos, 0)
        child2 = ttk.Label(self.paned, text='b')
        self.paned.add(child2)
        self.assertRaises(Tkinter.TclError, self.paned.sashpos, 1)

        self.paned.pack(expand=True, fill='both')
        self.paned.wait_visibility()

        curr_pos = self.paned.sashpos(0)
        self.paned.sashpos(0, 1000)
        self.assertTrue(curr_pos != self.paned.sashpos(0))
        self.assertTrue(isinstance(self.paned.sashpos(0), int)) 
Example #9
Source File: test_widgets.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_invoke(self):
        success = []
        def cb_test():
            success.append(1)
            return "cb test called"

        cbtn = ttk.Checkbutton(self.root, command=cb_test)
        # the variable automatically created by ttk.Checkbutton is actually
        # undefined till we invoke the Checkbutton
        self.assertEqual(cbtn.state(), ('alternate', ))
        self.assertRaises(tkinter.TclError, cbtn.tk.globalgetvar,
            cbtn['variable'])

        res = cbtn.invoke()
        self.assertEqual(res, "cb test called")
        self.assertEqual(cbtn['onvalue'],
            cbtn.tk.globalgetvar(cbtn['variable']))
        self.assertTrue(success)

        cbtn['command'] = ''
        res = cbtn.invoke()
        self.assertFalse(str(res))
        self.assertLessEqual(len(success), 1)
        self.assertEqual(cbtn['offvalue'],
            cbtn.tk.globalgetvar(cbtn['variable'])) 
Example #10
Source File: test_widgets.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_delete(self):
        self.assertRaises(Tkinter.TclError, self.tv.delete, '#0')

        item_id = self.tv.insert('', 'end')
        item2 = self.tv.insert(item_id, 'end')
        self.assertEqual(self.tv.get_children(), (item_id, ))
        self.assertEqual(self.tv.get_children(item_id), (item2, ))

        self.tv.delete(item_id)
        self.assertFalse(self.tv.get_children())

        # reattach should fail
        self.assertRaises(Tkinter.TclError,
            self.tv.reattach, item_id, '', 'end')

        # test multiple item delete
        item1 = self.tv.insert('', 'end')
        item2 = self.tv.insert('', 'end')
        self.assertEqual(self.tv.get_children(), (item1, item2))

        self.tv.delete(item1, item2)
        self.assertFalse(self.tv.get_children()) 
Example #11
Source File: test_widgets.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_heading(self):
        # check a dict is returned
        self.assertTrue(isinstance(self.tv.heading('#0'), dict))

        # check a value is returned
        self.tv.heading('#0', text='hi')
        self.assertEqual(self.tv.heading('#0', 'text'), 'hi')
        self.assertEqual(self.tv.heading('#0', text=None), 'hi')

        # invalid option
        self.assertRaises(Tkinter.TclError, self.tv.heading, '#0',
            background=None)
        # invalid value
        self.assertRaises(Tkinter.TclError, self.tv.heading, '#0',
            anchor=1)

    # XXX skipping for now; should be fixed to work with newer ttk 
Example #12
Source File: test_style.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_layout(self):
        style = self.style
        self.assertRaises(tkinter.TclError, style.layout, 'NotALayout')
        tv_style = style.layout('Treeview')

        # "erase" Treeview layout
        style.layout('Treeview', '')
        self.assertEqual(style.layout('Treeview'),
            [('null', {'sticky': 'nswe'})]
        )

        # restore layout
        style.layout('Treeview', tv_style)
        self.assertEqual(style.layout('Treeview'), tv_style)

        # should return a list
        self.assertIsInstance(style.layout('TButton'), list)

        # correct layout, but "option" doesn't exist as option
        self.assertRaises(tkinter.TclError, style.layout, 'Treeview',
            [('name', {'option': 'inexistent'})]) 
Example #13
Source File: widget_tests.py    From oss-ftp with MIT License 6 votes vote down vote up
def checkInvalidParam(self, widget, name, value, errmsg=None,
                          keep_orig=True):
        orig = widget[name]
        if errmsg is not None:
            errmsg = errmsg.format(value)
        with self.assertRaises(tkinter.TclError) as cm:
            widget[name] = value
        if errmsg is not None:
            self.assertEqual(str(cm.exception), errmsg)
        if keep_orig:
            self.assertEqual(widget[name], orig)
        else:
            widget[name] = orig
        with self.assertRaises(tkinter.TclError) as cm:
            widget.configure({name: value})
        if errmsg is not None:
            self.assertEqual(str(cm.exception), errmsg)
        if keep_orig:
            self.assertEqual(widget[name], orig)
        else:
            widget[name] = orig 
Example #14
Source File: test_loadtk.py    From BinderFilter with MIT License 6 votes vote down vote up
def testLoadTkFailure(self):
        old_display = None
        if sys.platform.startswith(('win', 'darwin', 'cygwin')):
            # no failure possible on windows?

            # XXX Maybe on tk older than 8.4.13 it would be possible,
            # see tkinter.h.
            return
        with test_support.EnvironmentVarGuard() as env:
            if 'DISPLAY' in os.environ:
                del env['DISPLAY']
                # on some platforms, deleting environment variables
                # doesn't actually carry through to the process level
                # because they don't support unsetenv
                # If that's the case, abort.
                display = os.popen('echo $DISPLAY').read().strip()
                if display:
                    return

            tcl = Tcl()
            self.assertRaises(TclError, tcl.winfo_geometry)
            self.assertRaises(TclError, tcl.loadtk) 
Example #15
Source File: test_text.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_search(self):
        text = self.text

        # pattern and index are obligatory arguments.
        self.assertRaises(Tkinter.TclError, text.search, None, '1.0')
        self.assertRaises(Tkinter.TclError, text.search, 'a', None)
        self.assertRaises(Tkinter.TclError, text.search, None, None)

        # Invalid text index.
        self.assertRaises(Tkinter.TclError, text.search, '', 0)

        # Check if we are getting the indices as strings -- you are likely
        # to get Tcl_Obj under Tk 8.5 if Tkinter doesn't convert it.
        text.insert('1.0', 'hi-test')
        self.assertEqual(text.search('-test', '1.0', 'end'), '1.2')
        self.assertEqual(text.search('test', '1.0', 'end'), '1.3') 
Example #16
Source File: backend_tkagg.py    From Computable with MIT License 6 votes vote down vote up
def showtip(self, text):
        "Display text in tooltip window"
        self.text = text
        if self.tipwindow or not self.text:
            return
        x, y, _, _ = self.widget.bbox("insert")
        x = x + self.widget.winfo_rootx() + 27
        y = y + self.widget.winfo_rooty()
        self.tipwindow = tw = Tk.Toplevel(self.widget)
        tw.wm_overrideredirect(1)
        tw.wm_geometry("+%d+%d" % (x, y))
        try:
            # For Mac OS
            tw.tk.call("::tk::unsupported::MacWindowStyle",
                       "style", tw._w,
                       "help", "noActivates")
        except Tk.TclError:
            pass
        label = Tk.Label(tw, text=self.text, justify=Tk.LEFT,
                      background="#ffffe0", relief=Tk.SOLID, borderwidth=1,
                      )
        label.pack(ipadx=1) 
Example #17
Source File: test_widgets.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_column(self):
        # return a dict with all options/values
        self.assertTrue(isinstance(self.tv.column('#0'), dict))
        # return a single value of the given option
        self.assertTrue(isinstance(self.tv.column('#0', width=None), int))
        # set a new value for an option
        self.tv.column('#0', width=10)
        # testing new way to get option value
        self.assertEqual(self.tv.column('#0', 'width'), 10)
        self.assertEqual(self.tv.column('#0', width=None), 10)
        # check read-only option
        self.assertRaises(Tkinter.TclError, self.tv.column, '#0', id='X')

        self.assertRaises(Tkinter.TclError, self.tv.column, 'invalid')
        invalid_kws = [
            {'unknown_option': 'some value'},  {'stretch': 'wrong'},
            {'anchor': 'wrong'}, {'width': 'wrong'}, {'minwidth': 'wrong'}
        ]
        for kw in invalid_kws:
            self.assertRaises(Tkinter.TclError, self.tv.column, '#0',
                **kw) 
Example #18
Source File: test_widgets.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_heading(self):
        # check a dict is returned
        self.assertIsInstance(self.tv.heading('#0'), dict)

        # check a value is returned
        self.tv.heading('#0', text='hi')
        self.assertEqual(self.tv.heading('#0', 'text'), 'hi')
        self.assertEqual(self.tv.heading('#0', text=None), 'hi')

        # invalid option
        self.assertRaises(tkinter.TclError, self.tv.heading, '#0',
            background=None)
        # invalid value
        self.assertRaises(tkinter.TclError, self.tv.heading, '#0',
            anchor=1) 
Example #19
Source File: ttk.py    From oss-ftp with MIT License 5 votes vote down vote up
def __init__(self, master, variable, default=None, *values, **kwargs):
        """Construct a themed OptionMenu widget with master as the parent,
        the resource textvariable set to variable, the initially selected
        value specified by the default parameter, the menu values given by
        *values and additional keywords.

        WIDGET-SPECIFIC OPTIONS

            style: stylename
                Menubutton style.
            direction: 'above', 'below', 'left', 'right', or 'flush'
                Menubutton direction.
            command: callback
                A callback that will be invoked after selecting an item.
        """
        kw = {'textvariable': variable, 'style': kwargs.pop('style', None),
              'direction': kwargs.pop('direction', None)}
        Menubutton.__init__(self, master, **kw)
        self['menu'] = Tkinter.Menu(self, tearoff=False)

        self._variable = variable
        self._callback = kwargs.pop('command', None)
        if kwargs:
            raise Tkinter.TclError('unknown option -%s' % (
                kwargs.iterkeys().next()))

        self.set_menu(default, *values) 
Example #20
Source File: turtle.py    From oss-ftp with MIT License 5 votes vote down vote up
def _iscolorstring(self, color):
        """Check if the string color is a legal Tkinter color string.
        """
        try:
            rgb = self.cv.winfo_rgb(color)
            ok = True
        except TK.TclError:
            ok = False
        return ok 
Example #21
Source File: test_widgets.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_set(self):
        self.tv['columns'] = ['A', 'B']
        item = self.tv.insert('', 'end', values=['a', 'b'])
        self.assertEqual(self.tv.set(item), {'A': 'a', 'B': 'b'})

        self.tv.set(item, 'B', 'a')
        self.assertEqual(self.tv.item(item, values=None),
                         ('a', 'a') if self.wantobjects else 'a a')

        self.tv['columns'] = ['B']
        self.assertEqual(self.tv.set(item), {'B': 'a'})

        self.tv.set(item, 'B', 'b')
        self.assertEqual(self.tv.set(item, column='B'), 'b')
        self.assertEqual(self.tv.item(item, values=None),
                         ('b', 'a') if self.wantobjects else 'b a')

        self.tv.set(item, 'B', 123)
        self.assertEqual(self.tv.set(item, 'B'),
                         123 if self.wantobjects else '123')
        self.assertEqual(self.tv.item(item, values=None),
                         (123, 'a') if self.wantobjects else '123 a')
        self.assertEqual(self.tv.set(item),
                         {'B': 123} if self.wantobjects else {'B': '123'})

        # inexistent column
        self.assertRaises(tkinter.TclError, self.tv.set, item, 'A')
        self.assertRaises(tkinter.TclError, self.tv.set, item, 'A', 'b')

        # inexistent item
        self.assertRaises(tkinter.TclError, self.tv.set, 'notme') 
Example #22
Source File: test_widgets.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_tag_configure(self):
        # Just testing parameter passing for now
        self.assertRaises(TypeError, self.tv.tag_configure)
        self.assertRaises(tkinter.TclError, self.tv.tag_configure,
            'test', sky='blue')
        self.tv.tag_configure('test', foreground='blue')
        self.assertEqual(str(self.tv.tag_configure('test', 'foreground')),
            'blue')
        self.assertEqual(str(self.tv.tag_configure('test', foreground=None)),
            'blue')
        self.assertIsInstance(self.tv.tag_configure('test'), dict) 
Example #23
Source File: test_widgets.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_index(self):
        # item 'what' doesn't exist
        self.assertRaises(tkinter.TclError, self.tv.index, 'what')

        self.assertEqual(self.tv.index(''), 0)

        item1 = self.tv.insert('', 'end')
        item2 = self.tv.insert('', 'end')
        c1 = self.tv.insert(item1, 'end')
        c2 = self.tv.insert(item1, 'end')
        self.assertEqual(self.tv.index(item1), 0)
        self.assertEqual(self.tv.index(c1), 0)
        self.assertEqual(self.tv.index(c2), 1)
        self.assertEqual(self.tv.index(item2), 1)

        self.tv.move(item2, '', 0)
        self.assertEqual(self.tv.index(item2), 0)
        self.assertEqual(self.tv.index(item1), 1)

        # check that index still works even after its parent and siblings
        # have been detached
        self.tv.detach(item1)
        self.assertEqual(self.tv.index(c2), 1)
        self.tv.detach(c1)
        self.assertEqual(self.tv.index(c2), 0)

        # but it fails after item has been deleted
        self.tv.delete(item1)
        self.assertRaises(tkinter.TclError, self.tv.index, c2) 
Example #24
Source File: test_extensions.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_widget_destroy(self):
        var = tkinter.StringVar(self.root)
        optmenu = ttk.OptionMenu(self.root, var)
        name = var._name
        optmenu.update_idletasks()
        optmenu.destroy()
        self.assertEqual(optmenu.tk.globalgetvar(name), var.get())
        del var
        self.assertRaises(tkinter.TclError, optmenu.tk.globalgetvar, name) 
Example #25
Source File: annotation_gui.py    From SEM with MIT License 5 votes vote down vote up
def handle_char(self, event):
        if self.adder is None:
            return
        if not self.adder.current_annotation:
            try:
                self.text.index("sel.first")
            except tkinter.TclError:
                return
        
        the_type = self.adder.type_from_letter(event.keysym)
        the_type = the_type or self.adder.type_from_letter(event.keysym.lower())
        if the_type is None:
            return
        if event.keysym.islower():
            fst = (self.charindex2position(self.adder.current_annotation.lb) if self.adder.current_annotation else self.text.index("sel.first"))
            lst = (self.charindex2position(self.adder.current_annotation.ub) if self.adder.current_annotation else self.text.index("sel.last"))
            self.wish_to_add = [self.adder.type_from_letter(event.keysym), fst, lst]
            self.add_annotation(event, remove_focus=False)
        else:
            if self.adder.current_annotation is not None:
                start = self.charindex2position(self.adder.current_annotation.lb)
                end = self.charindex2position(self.adder.current_annotation.ub)
            else:
                start, end = ("sel.first", "sel.last")
            try:
                for match in find_occurrences(self.text.get(start, end), self.doc.content, whole_word=self.whole_word):
                    cur_start, cur_end = self.charindex2position(match.start()), self.charindex2position(match.end())
                    if Tag(the_type, match.start(), match.end()) not in self.current_annotations:
                        self.wish_to_add = [the_type, cur_start, cur_end]
                        self.add_annotation(None, remove_focus=False)
            except tkinter.TclError:
                raise
            self.unselect() 
Example #26
Source File: test_extensions.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_initialization(self):
        self.assertRaises(tkinter.TclError,
            ttk.OptionMenu, self.root, self.textvar, invalid='thing')

        optmenu = ttk.OptionMenu(self.root, self.textvar, 'b', 'a', 'b')
        self.assertEqual(optmenu._variable.get(), 'b')

        self.assertTrue(optmenu['menu'])
        self.assertTrue(optmenu['textvariable'])

        optmenu.destroy() 
Example #27
Source File: test_widgets.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_widget_state(self):
        # XXX not sure about the portability of all these tests
        self.assertEqual(self.widget.state(), ())
        self.assertEqual(self.widget.instate(['!disabled']), True)

        # changing from !disabled to disabled
        self.assertEqual(self.widget.state(['disabled']), ('!disabled', ))
        # no state change
        self.assertEqual(self.widget.state(['disabled']), ())
        # change back to !disable but also active
        self.assertEqual(self.widget.state(['!disabled', 'active']),
            ('!active', 'disabled'))
        # no state changes, again
        self.assertEqual(self.widget.state(['!disabled', 'active']), ())
        self.assertEqual(self.widget.state(['active', '!disabled']), ())

        def test_cb(arg1, **kw):
            return arg1, kw
        self.assertEqual(self.widget.instate(['!disabled'],
            test_cb, "hi", **{"msg": "there"}),
            ('hi', {'msg': 'there'}))

        # attempt to set invalid statespec
        currstate = self.widget.state()
        self.assertRaises(tkinter.TclError, self.widget.instate,
            ['badstate'])
        self.assertRaises(tkinter.TclError, self.widget.instate,
            ['disabled', 'badstate'])
        # verify that widget didn't change its state
        self.assertEqual(currstate, self.widget.state())

        # ensuring that passing None as state doesn't modify current state
        self.widget.state(['active', '!disabled'])
        self.assertEqual(self.widget.state(), ('active', )) 
Example #28
Source File: support.py    From oss-ftp with MIT License 5 votes vote down vote up
def setUpClass(cls):
        cls._old_support_default_root = tkinter._support_default_root
        destroy_default_root()
        tkinter.NoDefaultRoot()
        cls.root = tkinter.Tk()
        cls.wantobjects = cls.root.wantobjects()
        # De-maximize main window.
        # Some window managers can maximize new windows.
        cls.root.wm_state('normal')
        try:
            cls.root.wm_attributes('-zoomed', False)
        except tkinter.TclError:
            pass 
Example #29
Source File: test_widgets.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_focus(self):
        # nothing is focused right now
        self.assertEqual(self.tv.focus(), '')

        item1 = self.tv.insert('', 'end')
        self.tv.focus(item1)
        self.assertEqual(self.tv.focus(), item1)

        self.tv.delete(item1)
        self.assertEqual(self.tv.focus(), '')

        # try focusing inexistent item
        self.assertRaises(tkinter.TclError, self.tv.focus, 'hi') 
Example #30
Source File: test_extensions.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_widget_destroy(self):
        # automatically created variable
        x = ttk.LabeledScale(self.root)
        var = x._variable._name
        x.destroy()
        self.assertRaises(tkinter.TclError, x.tk.globalgetvar, var)

        # manually created variable
        myvar = tkinter.DoubleVar(self.root)
        name = myvar._name
        x = ttk.LabeledScale(self.root, variable=myvar)
        x.destroy()
        if self.wantobjects:
            self.assertEqual(x.tk.globalgetvar(name), myvar.get())
        else:
            self.assertEqual(float(x.tk.globalgetvar(name)), myvar.get())
        del myvar
        self.assertRaises(tkinter.TclError, x.tk.globalgetvar, name)

        # checking that the tracing callback is properly removed
        myvar = tkinter.IntVar(self.root)
        # LabeledScale will start tracing myvar
        x = ttk.LabeledScale(self.root, variable=myvar)
        x.destroy()
        # Unless the tracing callback was removed, creating a new
        # LabeledScale with the same var will cause an error now. This
        # happens because the variable will be set to (possibly) a new
        # value which causes the tracing callback to be called and then
        # it tries calling instance attributes not yet defined.
        ttk.LabeledScale(self.root, variable=myvar)
        if hasattr(sys, 'last_type'):
            self.assertNotEqual(sys.last_type, tkinter.TclError)