Debian Codegraph @

Lib/test/test_ttk/test_widgets.py

raw
1 import unittest
2 import tkinter
3 from tkinter import ttk, TclError
4 from test.support import requires, gc_collect
5 import sys
6
7 from test.test_ttk_textonly import MockTclObj
8 from test.test_tkinter.support import setUpModule # noqa: F401
9 from test.test_tkinter.support import (
10 AbstractTkTest, requires_tk, tk_version, get_tk_patchlevel,
11 simulate_mouse_click, AbstractDefaultRootTest)
12 from test.test_tkinter.widget_tests import (add_standard_options,
13 AbstractWidgetTest, StandardOptionsTests, IntegerSizeTests, PixelSizeTests)
14
15 requires('gui')
16
17
18 class StandardTtkOptionsTests(StandardOptionsTests):
19
20 def test_configure_class(self):
21 widget = self.create()
22 self.assertEqual(widget['class'], '')
23 errmsg='attempt to change read-only option'
24 if get_tk_patchlevel(self.root) < (8, 6, 0, 'beta', 3):
25 errmsg='Attempt to change read-only option'
26 self.checkInvalidParam(widget, 'class', 'Foo', errmsg=errmsg)
27 widget2 = self.create(class_='Foo')
28 self.assertEqual(widget2['class'], 'Foo')
29
30 def test_configure_padding(self):
31 widget = self.create()
32 if get_tk_patchlevel(self.root) < (8, 6, 14):
33 def padding_conv(value):
34 self.assertIsInstance(value, tuple)
35 return tuple(map(str, value))
36 else:
37 padding_conv = None
38 self.checkParam(widget, 'padding', 0, expected=(0,), conv=padding_conv)
39 self.checkParam(widget, 'padding', 5, expected=(5,), conv=padding_conv)
40 self.checkParam(widget, 'padding', (5, 6),
41 expected=(5, 6), conv=padding_conv)
42 self.checkParam(widget, 'padding', (5, 6, 7),
43 expected=(5, 6, 7), conv=padding_conv)
44 self.checkParam(widget, 'padding', (5, 6, 7, 8),
45 expected=(5, 6, 7, 8), conv=padding_conv)
46 self.checkParam(widget, 'padding', ('5p', '6p', '7p', '8p'))
47 self.checkParam(widget, 'padding', (), expected='')
48
49 def test_configure_state(self):
50 widget = self.create()
51 self.checkParams(widget, 'state', 'active', 'disabled', 'readonly')
52
53 def test_configure_style(self):
54 widget = self.create()
55 self.assertEqual(widget['style'], '')
56 errmsg = 'Layout Foo not found'
57 if hasattr(self, 'default_orient'):
58 errmsg = ('Layout %s.Foo not found' %
59 getattr(self, 'default_orient').title())
60 self.checkInvalidParam(widget, 'style', 'Foo',
61 errmsg=errmsg)
62 widget2 = self.create(class_='Foo')
63 self.assertEqual(widget2['class'], 'Foo')
64 # XXX
65
66 def test_configure_relief(self):
67 widget = self.create()
68 self.checkReliefParam(widget, 'relief',
69 allow_empty=(tk_version >= (8, 7)))
70
71
72 class WidgetTest(AbstractTkTest, unittest.TestCase):
73 """Tests methods available in every ttk widget."""
74
75 def setUp(self):
76 super().setUp()
77 self.widget = ttk.Button(self.root, width=0, text="Text")
78 self.widget.pack()
79
80 def test_identify(self):
81 self.widget.update()
82 self.assertEqual(self.widget.identify(
83 int(self.widget.winfo_width() / 2),
84 int(self.widget.winfo_height() / 2)
85 ), "label")
86 self.assertEqual(self.widget.identify(-1, -1), "")
87
88 self.assertRaises(tkinter.TclError, self.widget.identify, None, 5)
89 self.assertRaises(tkinter.TclError, self.widget.identify, 5, None)
90 self.assertRaises(tkinter.TclError, self.widget.identify, 5, '')
91
92 def test_widget_state(self):
93 # XXX not sure about the portability of all these tests
94 self.assertEqual(self.widget.state(), ())
95 self.assertEqual(self.widget.instate(['!disabled']), True)
96
97 # changing from !disabled to disabled
98 self.assertEqual(self.widget.state(['disabled']), ('!disabled', ))
99 # no state change
100 self.assertEqual(self.widget.state(['disabled']), ())
101 # change back to !disable but also active
102 self.assertEqual(self.widget.state(['!disabled', 'active']),
103 ('!active', 'disabled'))
104 # no state changes, again
105 self.assertEqual(self.widget.state(['!disabled', 'active']), ())
106 self.assertEqual(self.widget.state(['active', '!disabled']), ())
107
108 def test_cb(arg1, **kw):
109 return arg1, kw
110 self.assertEqual(self.widget.instate(['!disabled'],
111 test_cb, "hi", **{"msg": "there"}),
112 ('hi', {'msg': 'there'}))
113
114 # attempt to set invalid statespec
115 currstate = self.widget.state()
116 self.assertRaises(tkinter.TclError, self.widget.instate,
117 ['badstate'])
118 self.assertRaises(tkinter.TclError, self.widget.instate,
119 ['disabled', 'badstate'])
120 # verify that widget didn't change its state
121 self.assertEqual(currstate, self.widget.state())
122
123 # ensuring that passing None as state doesn't modify current state
124 self.widget.state(['active', '!disabled'])
125 self.assertEqual(self.widget.state(), ('active', ))
126
127
128 class AbstractToplevelTest(AbstractWidgetTest, PixelSizeTests):
129 _conv_pixels = False
130
131
132 @add_standard_options(StandardTtkOptionsTests)
133 class FrameTest(AbstractToplevelTest, unittest.TestCase):
134 OPTIONS = (
135 'borderwidth', 'class', 'cursor', 'height',
136 'padding', 'relief', 'style', 'takefocus',
137 'width',
138 )
139
140 def create(self, **kwargs):
141 return ttk.Frame(self.root, **kwargs)
142
143
144 @add_standard_options(StandardTtkOptionsTests)
145 class LabelFrameTest(AbstractToplevelTest, unittest.TestCase):
146 OPTIONS = (
147 'borderwidth', 'class', 'cursor', 'height',
148 'labelanchor', 'labelwidget',
149 'padding', 'relief', 'style', 'takefocus',
150 'text', 'underline', 'width',
151 )
152
153 def create(self, **kwargs):
154 return ttk.LabelFrame(self.root, **kwargs)
155
156 def test_configure_labelanchor(self):
157 widget = self.create()
158 self.checkEnumParam(widget, 'labelanchor',
159 'e', 'en', 'es', 'n', 'ne', 'nw', 's', 'se', 'sw', 'w', 'wn', 'ws',
160 errmsg='Bad label anchor specification {}')
161 self.checkInvalidParam(widget, 'labelanchor', 'center')
162
163 def test_configure_labelwidget(self):
164 widget = self.create()
165 label = ttk.Label(self.root, text='Mupp', name='foo')
166 self.checkParam(widget, 'labelwidget', label, expected='.foo')
167 label.destroy()
168
169
170 class AbstractLabelTest(AbstractWidgetTest):
171 _allow_empty_justify = True
172
173 def checkImageParam(self, widget, name):
174 image = tkinter.PhotoImage(master=self.root, name='image1')
175 image2 = tkinter.PhotoImage(master=self.root, name='image2')
176 self.checkParam(widget, name, image, expected=('image1',))
177 self.checkParam(widget, name, 'image1', expected=('image1',))
178 self.checkParam(widget, name, (image,), expected=('image1',))
179 self.checkParam(widget, name, (image, 'active', image2),
180 expected=('image1', 'active', 'image2'))
181 self.checkParam(widget, name, 'image1 active image2',
182 expected=('image1', 'active', 'image2'))
183 self.checkInvalidParam(widget, name, 'spam',
184 errmsg='image "spam" doesn\'t exist')
185
186 def test_configure_compound(self):
187 values = ('none', 'text', 'image', 'center', 'top', 'bottom', 'left', 'right')
188 if tk_version >= (8, 7):
189 values += ('',)
190 widget = self.create()
191 self.checkEnumParam(widget, 'compound', *values, allow_empty=True)
192
193 test_configure_justify = requires_tk(8, 7)(StandardOptionsTests.test_configure_justify)
194
195 def test_configure_width(self):
196 widget = self.create()
197 self.checkParams(widget, 'width', 402, -402, 0)
198
199
200 @add_standard_options(StandardTtkOptionsTests)
201 class LabelTest(AbstractLabelTest, unittest.TestCase):
202 OPTIONS = (
203 'anchor', 'background', 'borderwidth',
204 'class', 'compound', 'cursor', 'font', 'foreground',
205 'image', 'justify', 'padding', 'relief', 'state', 'style',
206 'takefocus', 'text', 'textvariable',
207 'underline', 'width', 'wraplength',
208 )
209 _conv_pixels = False
210 _allow_empty_justify = tk_version >= (8, 7)
211
212 def create(self, **kwargs):
213 return ttk.Label(self.root, **kwargs)
214
215 test_configure_justify = StandardOptionsTests.test_configure_justify
216
217
218 @add_standard_options(StandardTtkOptionsTests)
219 class ButtonTest(AbstractLabelTest, unittest.TestCase):
220 OPTIONS = (
221 'class', 'command', 'compound', 'cursor', 'default',
222 'image', 'justify', 'padding', 'state', 'style',
223 'takefocus', 'text', 'textvariable',
224 'underline', 'width',
225 )
226
227 def create(self, **kwargs):
228 return ttk.Button(self.root, **kwargs)
229
230 def test_configure_default(self):
231 widget = self.create()
232 values = ('normal', 'active', 'disabled')
233 self.checkEnumParam(widget, 'default', *values,
234 sort=tk_version >= (8, 7))
235
236 def test_invoke(self):
237 success = []
238 btn = ttk.Button(self.root, command=lambda: success.append(1))
239 btn.invoke()
240 self.assertTrue(success)
241
242
243 @add_standard_options(StandardTtkOptionsTests)
244 class CheckbuttonTest(AbstractLabelTest, unittest.TestCase):
245 OPTIONS = (
246 'class', 'command', 'compound', 'cursor',
247 'image', 'justify',
248 'offvalue', 'onvalue',
249 'padding', 'state', 'style',
250 'takefocus', 'text', 'textvariable',
251 'underline', 'variable', 'width',
252 )
253
254 def create(self, **kwargs):
255 return ttk.Checkbutton(self.root, **kwargs)
256
257 def test_configure_offvalue(self):
258 widget = self.create()
259 self.checkParams(widget, 'offvalue', 1, 2.3, '', 'any string')
260
261 def test_configure_onvalue(self):
262 widget = self.create()
263 self.checkParams(widget, 'onvalue', 1, 2.3, '', 'any string')
264
265 def test_invoke(self):
266 success = []
267 def cb_test():
268 success.append(1)
269 return "cb test called"
270
271 cbtn = ttk.Checkbutton(self.root, command=cb_test)
272 # the variable automatically created by ttk.Checkbutton is actually
273 # undefined till we invoke the Checkbutton
274 self.assertEqual(cbtn.state(), ('alternate', ))
275 self.assertRaises(tkinter.TclError, cbtn.tk.globalgetvar,
276 cbtn['variable'])
277
278 res = cbtn.invoke()
279 self.assertEqual(res, "cb test called")
280 self.assertEqual(cbtn['onvalue'],
281 cbtn.tk.globalgetvar(cbtn['variable']))
282 self.assertTrue(success)
283
284 cbtn['command'] = ''
285 res = cbtn.invoke()
286 if tk_version >= (8, 7) and self.wantobjects:
287 self.assertEqual(res, ())
288 else:
289 self.assertEqual(str(res), '')
290 self.assertLessEqual(len(success), 1)
291 self.assertEqual(cbtn['offvalue'],
292 cbtn.tk.globalgetvar(cbtn['variable']))
293
294 def test_unique_variables(self):
295 frames = []
296 buttons = []
297 for i in range(2):
298 f = ttk.Frame(self.root)
299 f.pack()
300 frames.append(f)
301 for j in 'AB':
302 b = ttk.Checkbutton(f, text=j)
303 b.pack()
304 buttons.append(b)
305 variables = [str(b['variable']) for b in buttons]
306 self.assertEqual(len(set(variables)), 4, variables)
307
308 def test_unique_variables2(self):
309 buttons = []
310 f = ttk.Frame(self.root)
311 f.pack()
312 f = ttk.Frame(self.root)
313 f.pack()
314 for j in 'AB':
315 b = tkinter.Checkbutton(f, text=j)
316 b.pack()
317 buttons.append(b)
318 # Should be larger than the number of all previously created
319 # tkinter.Checkbutton widgets:
320 for j in range(100):
321 b = ttk.Checkbutton(f, text=str(j))
322 b.pack()
323 buttons.append(b)
324 names = [str(b) for b in buttons]
325 self.assertEqual(len(set(names)), len(buttons), names)
326 variables = [str(b['variable']) for b in buttons]
327 self.assertEqual(len(set(variables)), len(buttons), variables)
328
329
330 @add_standard_options(IntegerSizeTests, StandardTtkOptionsTests)
331 class EntryTest(AbstractWidgetTest, unittest.TestCase):
332 OPTIONS = (
333 'background', 'class', 'cursor',
334 'exportselection', 'font', 'foreground',
335 'invalidcommand', 'justify',
336 'placeholder', 'placeholderforeground',
337 'show', 'state', 'style', 'takefocus', 'textvariable',
338 'validate', 'validatecommand', 'width', 'xscrollcommand',
339 )
340 # bpo-27313: macOS Tk/Tcl may or may not report 'Entry.field'.
341 IDENTIFY_AS = {'Entry.field', 'textarea'}
342
343 def setUp(self):
344 super().setUp()
345 self.entry = self.create()
346
347 def create(self, **kwargs):
348 return ttk.Entry(self.root, **kwargs)
349
350 def test_configure_invalidcommand(self):
351 widget = self.create()
352 self.checkCommandParam(widget, 'invalidcommand')
353
354 def test_configure_show(self):
355 widget = self.create()
356 self.checkParam(widget, 'show', '*')
357 self.checkParam(widget, 'show', '')
358 self.checkParam(widget, 'show', ' ')
359
360 def test_configure_validate(self):
361 widget = self.create()
362 self.checkEnumParam(widget, 'validate',
363 'all', 'key', 'focus', 'focusin', 'focusout', 'none')
364
365 def test_configure_validatecommand(self):
366 widget = self.create()
367 self.checkCommandParam(widget, 'validatecommand')
368
369 def test_bbox(self):
370 self.assertIsBoundingBox(self.entry.bbox(0))
371 self.assertRaises(tkinter.TclError, self.entry.bbox, 'noindex')
372 self.assertRaises(tkinter.TclError, self.entry.bbox, None)
373
374 def test_identify(self):
375 self.entry.pack()
376 self.entry.update()
377
378 self.assertIn(self.entry.identify(5, 5), self.IDENTIFY_AS)
379 self.assertEqual(self.entry.identify(-1, -1), "")
380
381 self.assertRaises(tkinter.TclError, self.entry.identify, None, 5)
382 self.assertRaises(tkinter.TclError, self.entry.identify, 5, None)
383 self.assertRaises(tkinter.TclError, self.entry.identify, 5, '')
384
385 def test_validation_options(self):
386 success = []
387 test_invalid = lambda: success.append(True)
388
389 self.entry['validate'] = 'none'
390 self.entry['validatecommand'] = lambda: False
391
392 self.entry['invalidcommand'] = test_invalid
393 self.entry.validate()
394 self.assertTrue(success)
395
396 self.entry['invalidcommand'] = ''
397 self.entry.validate()
398 self.assertEqual(len(success), 1)
399
400 self.entry['invalidcommand'] = test_invalid
401 self.entry['validatecommand'] = lambda: True
402 self.entry.validate()
403 self.assertEqual(len(success), 1)
404
405 self.entry['validatecommand'] = ''
406 self.entry.validate()
407 self.assertEqual(len(success), 1)
408
409 self.entry['validatecommand'] = True
410 self.assertRaises(tkinter.TclError, self.entry.validate)
411
412 def test_validation(self):
413 validation = []
414 def validate(to_insert):
415 if not 'a' <= to_insert.lower() <= 'z':
416 validation.append(False)
417 return False
418 validation.append(True)
419 return True
420
421 self.entry['validate'] = 'key'
422 self.entry['validatecommand'] = self.entry.register(validate), '%S'
423
424 self.entry.insert('end', 1)
425 self.entry.insert('end', 'a')
426 self.assertEqual(validation, [False, True])
427 self.assertEqual(self.entry.get(), 'a')
428
429 def test_revalidation(self):
430 def validate(content):
431 for letter in content:
432 if not 'a' <= letter.lower() <= 'z':
433 return False
434 return True
435
436 self.entry['validatecommand'] = self.entry.register(validate), '%P'
437
438 self.entry.insert('end', 'avocado')
439 self.assertEqual(self.entry.validate(), True)
440 self.assertEqual(self.entry.state(), ())
441
442 self.entry.delete(0, 'end')
443 self.assertEqual(self.entry.get(), '')
444
445 self.entry.insert('end', 'a1b')
446 self.assertEqual(self.entry.validate(), False)
447 self.assertEqual(self.entry.state(), ('invalid', ))
448
449 self.entry.delete(1)
450 self.assertEqual(self.entry.validate(), True)
451 self.assertEqual(self.entry.state(), ())
452
453
454 @add_standard_options(IntegerSizeTests, StandardTtkOptionsTests)
455 class ComboboxTest(EntryTest, unittest.TestCase):
456 OPTIONS = (
457 'background', 'class', 'cursor', 'exportselection',
458 'font', 'foreground', 'height', 'invalidcommand',
459 'justify', 'placeholder', 'placeholderforeground', 'postcommand',
460 'show', 'state', 'style',
461 'takefocus', 'textvariable',
462 'validate', 'validatecommand', 'values',
463 'width', 'xscrollcommand',
464 )
465 IDENTIFY_AS = {'Combobox.button', 'textarea'}
466
467 def setUp(self):
468 super().setUp()
469 self.combo = self.create()
470
471 def create(self, **kwargs):
472 return ttk.Combobox(self.root, **kwargs)
473
474 def test_configure_height(self):
475 widget = self.create()
476 self.checkParams(widget, 'height', 100, 101.2, 102.6, -100, 0, '1i')
477
478 def _show_drop_down_listbox(self):
479 width = self.combo.winfo_width()
480 x, y = width - 5, 5
481 if sys.platform != 'darwin': # there's no down arrow on macOS
482 self.assertRegex(self.combo.identify(x, y), r'.*downarrow\Z')
483 self.combo.event_generate('<ButtonPress-1>', x=x, y=y)
484 self.combo.event_generate('<ButtonRelease-1>', x=x, y=y)
485 self.combo.update_idletasks()
486
487 def test_virtual_event(self):
488 success = []
489
490 self.combo['values'] = [1]
491 self.combo.bind('<<ComboboxSelected>>',
492 lambda evt: success.append(True))
493 self.combo.pack()
494 self.combo.update()
495
496 height = self.combo.winfo_height()
497 self._show_drop_down_listbox()
498 self.combo.update()
499 self.combo.event_generate('<Return>')
500 self.combo.update()
501
502 self.assertTrue(success)
503
504 def test_configure_postcommand(self):
505 success = []
506
507 self.combo['postcommand'] = lambda: success.append(True)
508 self.combo.pack()
509 self.combo.update()
510
511 self._show_drop_down_listbox()
512 self.assertTrue(success)
513
514 # testing postcommand removal
515 self.combo['postcommand'] = ''
516 self._show_drop_down_listbox()
517 self.assertEqual(len(success), 1)
518
519 def test_configure_values(self):
520 def check_get_current(getval, currval):
521 self.assertEqual(self.combo.get(), getval)
522 self.assertEqual(self.combo.current(), currval)
523
524 self.assertIn(self.combo['values'], ((), ''))
525 check_get_current('', -1)
526
527 self.checkParam(self.combo, 'values', 'mon tue wed thur',
528 expected=('mon', 'tue', 'wed', 'thur'))
529 self.checkParam(self.combo, 'values', ('mon', 'tue', 'wed', 'thur'))
530 self.checkParam(self.combo, 'values', (42, 3.14, '', 'any string'))
531 self.checkParam(self.combo, 'values', '')
532
533 self.combo['values'] = ['a', 1, 'c']
534
535 self.combo.set('c')
536 check_get_current('c', 2)
537
538 self.combo.current(0)
539 check_get_current('a', 0)
540
541 self.combo.set('d')
542 check_get_current('d', -1)
543
544 # testing values with empty string
545 self.combo.set('')
546 self.combo['values'] = (1, 2, '', 3)
547 check_get_current('', 2)
548
549 # testing values with empty string set through configure
550 self.combo.configure(values=[1, '', 2])
551 self.assertEqual(self.combo['values'],
552 ('1', '', '2') if self.wantobjects else
553 '1 {} 2')
554
555 # testing values with spaces
556 self.combo['values'] = ['a b', 'a\tb', 'a\nb']
557 self.assertEqual(self.combo['values'],
558 ('a b', 'a\tb', 'a\nb') if self.wantobjects else
559 '{a b} {a\tb} {a\nb}')
560
561 # testing values with special characters
562 self.combo['values'] = [r'a\tb', '"a"', '} {']
563 self.assertEqual(self.combo['values'],
564 (r'a\tb', '"a"', '} {') if self.wantobjects else
565 r'a\\tb {"a"} \}\ \{')
566
567 # out of range
568 self.assertRaises(tkinter.TclError, self.combo.current,
569 len(self.combo['values']))
570 # it expects an integer (or something that can be converted to int)
571 self.assertRaises(tkinter.TclError, self.combo.current, '')
572
573 # testing creating combobox with empty string in values
574 combo2 = ttk.Combobox(self.root, values=[1, 2, ''])
575 self.assertEqual(combo2['values'],
576 ('1', '2', '') if self.wantobjects else '1 2 {}')
577 combo2.destroy()
578
579
580 @add_standard_options(IntegerSizeTests, StandardTtkOptionsTests)
581 class PanedWindowTest(AbstractWidgetTest, unittest.TestCase):
582 OPTIONS = (
583 'class', 'cursor', 'height',
584 'orient', 'style', 'takefocus', 'width',
585 )
586
587 def setUp(self):
588 super().setUp()
589 self.paned = self.create()
590
591 def create(self, **kwargs):
592 return ttk.PanedWindow(self.root, **kwargs)
593
594 def test_configure_orient(self):
595 widget = self.create()
596 self.assertEqual(str(widget['orient']), 'vertical')
597 errmsg='attempt to change read-only option'
598 if get_tk_patchlevel(self.root) < (8, 6, 0, 'beta', 3):
599 errmsg='Attempt to change read-only option'
600 self.checkInvalidParam(widget, 'orient', 'horizontal',
601 errmsg=errmsg)
602 widget2 = self.create(orient='horizontal')
603 self.assertEqual(str(widget2['orient']), 'horizontal')
604
605 def test_add(self):
606 # attempt to add a child that is not a direct child of the paned window
607 label = ttk.Label(self.paned)
608 child = ttk.Label(label)
609 self.assertRaises(tkinter.TclError, self.paned.add, child)
610 label.destroy()
611 child.destroy()
612 # another attempt
613 label = ttk.Label(self.root)
614 child = ttk.Label(label)
615 self.assertRaises(tkinter.TclError, self.paned.add, child)
616 child.destroy()
617 label.destroy()
618
619 good_child = ttk.Label(self.root)
620 self.paned.add(good_child)
621 # re-adding a child is not accepted
622 self.assertRaises(tkinter.TclError, self.paned.add, good_child)
623
624 other_child = ttk.Label(self.paned)
625 self.paned.add(other_child)
626 self.assertEqual(self.paned.pane(0), self.paned.pane(1))
627 self.assertRaises(tkinter.TclError, self.paned.pane, 2)
628 good_child.destroy()
629 other_child.destroy()
630 self.assertRaises(tkinter.TclError, self.paned.pane, 0)
631
632 def test_forget(self):
633 self.assertRaises(tkinter.TclError, self.paned.forget, None)
634 self.assertRaises(tkinter.TclError, self.paned.forget, 0)
635
636 self.paned.add(ttk.Label(self.root))
637 self.paned.forget(0)
638 self.assertRaises(tkinter.TclError, self.paned.forget, 0)
639
640 def test_insert(self):
641 self.assertRaises(tkinter.TclError, self.paned.insert, None, 0)
642 self.assertRaises(tkinter.TclError, self.paned.insert, 0, None)
643 self.assertRaises(tkinter.TclError, self.paned.insert, 0, 0)
644
645 child = ttk.Label(self.root)
646 child2 = ttk.Label(self.root)
647 child3 = ttk.Label(self.root)
648
649 if tk_version >= (8, 7):
650 self.paned.insert(0, child)
651 self.assertEqual(self.paned.panes(), (str(child),))
652 self.paned.forget(0)
653 else:
654 self.assertRaises(tkinter.TclError, self.paned.insert, 0, child)
655
656 self.assertEqual(self.paned.panes(), ())
657 self.paned.insert('end', child2)
658 self.paned.insert(0, child)
659 self.assertEqual(self.paned.panes(), (str(child), str(child2)))
660
661 self.paned.insert(0, child2)
662 self.assertEqual(self.paned.panes(), (str(child2), str(child)))
663
664 self.paned.insert('end', child3)
665 self.assertEqual(self.paned.panes(),
666 (str(child2), str(child), str(child3)))
667
668 # reinserting a child should move it to its current position
669 panes = self.paned.panes()
670 self.paned.insert('end', child3)
671 self.assertEqual(panes, self.paned.panes())
672
673 # moving child3 to child2 position should result in child2 ending up
674 # in previous child position and child ending up in previous child3
675 # position
676 self.paned.insert(child2, child3)
677 self.assertEqual(self.paned.panes(),
678 (str(child3), str(child2), str(child)))
679
680 def test_pane(self):
681 self.assertRaises(tkinter.TclError, self.paned.pane, 0)
682
683 child = ttk.Label(self.root)
684 self.paned.add(child)
685 self.assertIsInstance(self.paned.pane(0), dict)
686 self.assertEqual(self.paned.pane(0, weight=None),
687 0 if self.wantobjects else '0')
688 # newer form for querying a single option
689 self.assertEqual(self.paned.pane(0, 'weight'),
690 0 if self.wantobjects else '0')
691 self.assertEqual(self.paned.pane(0), self.paned.pane(str(child)))
692
693 self.assertRaises(tkinter.TclError, self.paned.pane, 0,
694 badoption='somevalue')
695
696 def test_sashpos(self):
697 self.assertRaises(tkinter.TclError, self.paned.sashpos, None)
698 self.assertRaises(tkinter.TclError, self.paned.sashpos, '')
699 self.assertRaises(tkinter.TclError, self.paned.sashpos, 0)
700
701 child = ttk.Label(self.paned, text='a')
702 self.paned.add(child, weight=1)
703 self.assertRaises(tkinter.TclError, self.paned.sashpos, 0)
704 child2 = ttk.Label(self.paned, text='b')
705 self.paned.add(child2)
706 self.assertRaises(tkinter.TclError, self.paned.sashpos, 1)
707
708 self.paned.pack(expand=True, fill='both')
709
710 curr_pos = self.paned.sashpos(0)
711 self.paned.sashpos(0, 1000)
712 self.assertNotEqual(curr_pos, self.paned.sashpos(0))
713 self.assertIsInstance(self.paned.sashpos(0), int)
714
715
716 @add_standard_options(StandardTtkOptionsTests)
717 class RadiobuttonTest(AbstractLabelTest, unittest.TestCase):
718 OPTIONS = (
719 'class', 'command', 'compound', 'cursor',
720 'image', 'justify',
721 'padding', 'state', 'style',
722 'takefocus', 'text', 'textvariable',
723 'underline', 'value', 'variable', 'width',
724 )
725
726 def create(self, **kwargs):
727 return ttk.Radiobutton(self.root, **kwargs)
728
729 def test_configure_value(self):
730 widget = self.create()
731 self.checkParams(widget, 'value', 1, 2.3, '', 'any string')
732
733 def test_configure_invoke(self):
734 success = []
735 def cb_test():
736 success.append(1)
737 return "cb test called"
738
739 myvar = tkinter.IntVar(self.root)
740 cbtn = ttk.Radiobutton(self.root, command=cb_test,
741 variable=myvar, value=0)
742 cbtn2 = ttk.Radiobutton(self.root, command=cb_test,
743 variable=myvar, value=1)
744
745 if self.wantobjects:
746 conv = lambda x: x
747 else:
748 conv = int
749
750 res = cbtn.invoke()
751 self.assertEqual(res, "cb test called")
752 self.assertEqual(conv(cbtn['value']), myvar.get())
753 self.assertEqual(myvar.get(),
754 conv(cbtn.tk.globalgetvar(cbtn['variable'])))
755 self.assertTrue(success)
756
757 cbtn2['command'] = ''
758 res = cbtn2.invoke()
759 if tk_version >= (8, 7) and self.wantobjects:
760 self.assertEqual(res, ())
761 else:
762 self.assertEqual(str(res), '')
763 self.assertLessEqual(len(success), 1)
764 self.assertEqual(conv(cbtn2['value']), myvar.get())
765 self.assertEqual(myvar.get(),
766 conv(cbtn.tk.globalgetvar(cbtn['variable'])))
767
768 self.assertEqual(str(cbtn['variable']), str(cbtn2['variable']))
769
770
771 class MenubuttonTest(AbstractLabelTest, unittest.TestCase):
772 OPTIONS = (
773 'class', 'compound', 'cursor', 'direction',
774 'image', 'justify', 'menu', 'padding', 'state', 'style',
775 'takefocus', 'text', 'textvariable',
776 'underline', 'width',
777 )
778
779 def create(self, **kwargs):
780 return ttk.Menubutton(self.root, **kwargs)
781
782 def test_configure_direction(self):
783 widget = self.create()
784 values = ('above', 'below', 'left', 'right', 'flush')
785 self.checkEnumParam(widget, 'direction', *values,
786 sort=tk_version >= (8, 7))
787
788 def test_configure_menu(self):
789 widget = self.create()
790 menu = tkinter.Menu(widget, name='menu')
791 self.checkParam(widget, 'menu', menu, conv=str)
792 menu.destroy()
793
794
795 @add_standard_options(StandardTtkOptionsTests)
796 class ScaleTest(AbstractWidgetTest, unittest.TestCase):
797 OPTIONS = (
798 'class', 'command', 'cursor', 'from', 'length',
799 'orient', 'state', 'style', 'takefocus', 'to', 'value', 'variable',
800 )
801 _conv_pixels = False
802 default_orient = 'horizontal'
803
804 def setUp(self):
805 super().setUp()
806 self.scale = self.create()
807 self.scale.pack()
808 self.scale.update()
809
810 def create(self, **kwargs):
811 return ttk.Scale(self.root, **kwargs)
812
813 def test_configure_from(self):
814 widget = self.create()
815 self.checkFloatParam(widget, 'from', 100, 14.9, 15.1, conv=False)
816
817 def test_configure_length(self):
818 widget = self.create()
819 self.checkPixelsParam(widget, 'length', 130, 131.2, 135.6, '5i')
820
821 test_configure_state = requires_tk(8, 6, 9)(StandardTtkOptionsTests.test_configure_state)
822
823 def test_configure_to(self):
824 widget = self.create()
825 self.checkFloatParam(widget, 'to', 300, 14.9, 15.1, -10, conv=False)
826
827 def test_configure_value(self):
828 widget = self.create()
829 self.checkFloatParam(widget, 'value', 300, 14.9, 15.1, -10, conv=False)
830
831 def test_custom_event(self):
832 failure = [1, 1, 1] # will need to be empty
833
834 funcid = self.scale.bind('<<RangeChanged>>', lambda evt: failure.pop())
835
836 self.scale['from'] = 10
837 self.scale['from_'] = 10
838 self.scale['to'] = 3
839
840 self.assertFalse(failure)
841
842 failure = [1, 1, 1]
843 self.scale.configure(from_=2, to=5)
844 self.scale.configure(from_=0, to=-2)
845 self.scale.configure(to=10)
846
847 self.assertFalse(failure)
848
849 def test_get(self):
850 if self.wantobjects:
851 conv = lambda x: x
852 else:
853 conv = float
854
855 scale_width = self.scale.winfo_width()
856 self.assertEqual(self.scale.get(scale_width, 0), self.scale['to'])
857
858 self.assertEqual(conv(self.scale.get(0, 0)), conv(self.scale['from']))
859 self.assertEqual(self.scale.get(), self.scale['value'])
860 self.scale['value'] = 30
861 self.assertEqual(self.scale.get(), self.scale['value'])
862
863 self.assertRaises(tkinter.TclError, self.scale.get, '', 0)
864 self.assertRaises(tkinter.TclError, self.scale.get, 0, '')
865
866 def test_set(self):
867 if self.wantobjects:
868 conv = lambda x: x
869 else:
870 conv = float
871
872 # set restricts the max/min values according to the current range
873 max = conv(self.scale['to'])
874 new_max = max + 10
875 self.scale.set(new_max)
876 self.assertEqual(conv(self.scale.get()), max)
877 min = conv(self.scale['from'])
878 self.scale.set(min - 1)
879 self.assertEqual(conv(self.scale.get()), min)
880
881 # changing directly the variable doesn't impose this limitation tho
882 var = tkinter.DoubleVar(self.root)
883 self.scale['variable'] = var
884 var.set(max + 5)
885 self.assertEqual(conv(self.scale.get()), var.get())
886 self.assertEqual(conv(self.scale.get()), max + 5)
887 del var
888 gc_collect() # For PyPy or other GCs.
889
890 # the same happens with the value option
891 self.scale['value'] = max + 10
892 self.assertEqual(conv(self.scale.get()), max + 10)
893 self.assertEqual(conv(self.scale.get()), conv(self.scale['value']))
894
895 # nevertheless, note that the max/min values we can get specifying
896 # x, y coords are the ones according to the current range
897 self.assertEqual(conv(self.scale.get(0, 0)), min)
898 self.assertEqual(conv(self.scale.get(self.scale.winfo_width(), 0)), max)
899
900 self.assertRaises(tkinter.TclError, self.scale.set, None)
901
902
903 @add_standard_options(StandardTtkOptionsTests)
904 class ProgressbarTest(AbstractWidgetTest, unittest.TestCase):
905 OPTIONS = (
906 'anchor', 'class', 'cursor', 'font', 'foreground', 'justify',
907 'orient', 'length',
908 'mode', 'maximum', 'phase', 'text', 'wraplength',
909 'style', 'takefocus', 'value', 'variable',
910 )
911 _conv_pixels = False
912 _allow_empty_justify = True
913 default_orient = 'horizontal'
914
915 def create(self, **kwargs):
916 return ttk.Progressbar(self.root, **kwargs)
917
918 @requires_tk(8, 7)
919 def test_configure_anchor(self):
920 widget = self.create()
921 self.checkEnumParam(widget, 'anchor',
922 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', 'center', '')
923
924 test_configure_font = requires_tk(8, 7)(StandardOptionsTests.test_configure_font)
925 test_configure_foreground = requires_tk(8, 7)(StandardOptionsTests.test_configure_foreground)
926 test_configure_justify = requires_tk(8, 7)(StandardTtkOptionsTests.test_configure_justify)
927
928 def test_configure_length(self):
929 widget = self.create()
930 self.checkPixelsParam(widget, 'length', 100.1, 56.7, '2i')
931
932 def test_configure_maximum(self):
933 widget = self.create()
934 self.checkFloatParam(widget, 'maximum', 150.2, 77.7, 0, -10, conv=False)
935
936 def test_configure_mode(self):
937 widget = self.create()
938 self.checkEnumParam(widget, 'mode', 'determinate', 'indeterminate')
939
940 def test_configure_phase(self):
941 # XXX
942 pass
943
944 test_configure_text = requires_tk(8, 7)(StandardOptionsTests.test_configure_text)
945
946 def test_configure_value(self):
947 widget = self.create()
948 self.checkFloatParam(widget, 'value', 150.2, 77.7, 0, -10,
949 conv=False)
950
951 test_configure_wraplength = requires_tk(8, 7)(StandardOptionsTests.test_configure_wraplength)
952
953
954 @unittest.skipIf(sys.platform == 'darwin',
955 'ttk.Scrollbar is special on MacOSX')
956 @add_standard_options(StandardTtkOptionsTests)
957 class ScrollbarTest(AbstractWidgetTest, unittest.TestCase):
958 OPTIONS = (
959 'class', 'command', 'cursor', 'orient', 'style', 'takefocus',
960 )
961 default_orient = 'vertical'
962
963 def create(self, **kwargs):
964 return ttk.Scrollbar(self.root, **kwargs)
965
966
967 @add_standard_options(StandardTtkOptionsTests)
968 class NotebookTest(AbstractWidgetTest, unittest.TestCase):
969 OPTIONS = (
970 'class', 'cursor', 'height', 'padding', 'style', 'takefocus', 'width',
971 )
972 if tk_version >= (8, 7):
973 _conv_pixels = False
974
975 def setUp(self):
976 super().setUp()
977 self.nb = self.create(padding=0)
978 self.child1 = ttk.Label(self.root)
979 self.child2 = ttk.Label(self.root)
980 self.nb.add(self.child1, text='a')
981 self.nb.add(self.child2, text='b')
982
983 def create(self, **kwargs):
984 return ttk.Notebook(self.root, **kwargs)
985
986 def test_configure_height(self):
987 widget = self.create()
988 if get_tk_patchlevel(self.root) < (8, 6, 15):
989 self.checkIntegerParam(widget, 'height', 402, -402, 0)
990 else:
991 self.checkPixelsParam(widget, 'height', '10c', 402, -402, 0, conv=False)
992
993 def test_configure_width(self):
994 widget = self.create()
995 if get_tk_patchlevel(self.root) < (8, 6, 15):
996 self.checkIntegerParam(widget, 'width', 402, -402, 0)
997 else:
998 self.checkPixelsParam(widget, 'width', '10c', 402, -402, 0, conv=False)
999
1000 def test_tab_identifiers(self):
1001 self.nb.forget(0)
1002 self.nb.hide(self.child2)
1003 self.assertRaises(tkinter.TclError, self.nb.tab, self.child1)
1004 self.assertEqual(self.nb.index('end'), 1)
1005 self.nb.add(self.child2)
1006 self.assertEqual(self.nb.index('end'), 1)
1007 self.nb.select(self.child2)
1008
1009 self.assertTrue(self.nb.tab('current'))
1010 self.nb.add(self.child1, text='a')
1011
1012 self.nb.pack()
1013 self.nb.update()
1014 if sys.platform == 'darwin':
1015 tb_idx = "@20,5"
1016 else:
1017 tb_idx = "@5,5"
1018 self.assertEqual(self.nb.tab(tb_idx), self.nb.tab('current'))
1019
1020 for i in range(5, 100, 5):
1021 try:
1022 if self.nb.tab('@%d, 5' % i, text=None) == 'a':
1023 break
1024 except tkinter.TclError:
1025 pass
1026
1027 else:
1028 self.fail("Tab with text 'a' not found")
1029
1030 def test_add_and_hidden(self):
1031 self.assertRaises(tkinter.TclError, self.nb.hide, -1)
1032 self.assertRaises(tkinter.TclError, self.nb.hide, 'hi')
1033 self.assertRaises(tkinter.TclError, self.nb.hide, None)
1034 self.assertRaises(tkinter.TclError, self.nb.add, None)
1035 self.assertRaises(tkinter.TclError, self.nb.add, ttk.Label(self.root),
1036 unknown='option')
1037
1038 tabs = self.nb.tabs()
1039 self.nb.hide(self.child1)
1040 self.nb.add(self.child1)
1041 self.assertEqual(self.nb.tabs(), tabs)
1042
1043 child = ttk.Label(self.root)
1044 self.nb.add(child, text='c')
1045 tabs = self.nb.tabs()
1046
1047 curr = self.nb.index('current')
1048 # verify that the tab gets re-added at its previous position
1049 child2_index = self.nb.index(self.child2)
1050 self.nb.hide(self.child2)
1051 self.nb.add(self.child2)
1052 self.assertEqual(self.nb.tabs(), tabs)
1053 self.assertEqual(self.nb.index(self.child2), child2_index)
1054 self.assertEqual(str(self.child2), self.nb.tabs()[child2_index])
1055 # but the tab next to it (not hidden) is the one selected now
1056 self.assertEqual(self.nb.index('current'), curr + 1)
1057
1058 def test_forget(self):
1059 self.assertRaises(tkinter.TclError, self.nb.forget, -1)
1060 self.assertRaises(tkinter.TclError, self.nb.forget, 'hi')
1061 self.assertRaises(tkinter.TclError, self.nb.forget, None)
1062
1063 tabs = self.nb.tabs()
1064 child1_index = self.nb.index(self.child1)
1065 self.nb.forget(self.child1)
1066 self.assertNotIn(str(self.child1), self.nb.tabs())
1067 self.assertEqual(len(tabs) - 1, len(self.nb.tabs()))
1068
1069 self.nb.add(self.child1)
1070 self.assertEqual(self.nb.index(self.child1), 1)
1071 self.assertNotEqual(child1_index, self.nb.index(self.child1))
1072
1073 def test_index(self):
1074 self.assertRaises(tkinter.TclError, self.nb.index, -1)
1075 self.assertRaises(tkinter.TclError, self.nb.index, None)
1076
1077 self.assertIsInstance(self.nb.index('end'), int)
1078 self.assertEqual(self.nb.index(self.child1), 0)
1079 self.assertEqual(self.nb.index(self.child2), 1)
1080 self.assertEqual(self.nb.index('end'), 2)
1081
1082 def test_insert(self):
1083 # moving tabs
1084 tabs = self.nb.tabs()
1085 self.nb.insert(1, tabs[0])
1086 self.assertEqual(self.nb.tabs(), (tabs[1], tabs[0]))
1087 self.nb.insert(self.child1, self.child2)
1088 self.assertEqual(self.nb.tabs(), tabs)
1089 self.nb.insert('end', self.child1)
1090 self.assertEqual(self.nb.tabs(), (tabs[1], tabs[0]))
1091 self.nb.insert('end', 0)
1092 self.assertEqual(self.nb.tabs(), tabs)
1093 # bad moves
1094 self.assertRaises(tkinter.TclError, self.nb.insert, 2, tabs[0])
1095 self.assertRaises(tkinter.TclError, self.nb.insert, -1, tabs[0])
1096
1097 # new tab
1098 child3 = ttk.Label(self.root)
1099 self.nb.insert(1, child3)
1100 self.assertEqual(self.nb.tabs(), (tabs[0], str(child3), tabs[1]))
1101 self.nb.forget(child3)
1102 self.assertEqual(self.nb.tabs(), tabs)
1103 self.nb.insert(self.child1, child3)
1104 self.assertEqual(self.nb.tabs(), (str(child3), ) + tabs)
1105 self.nb.forget(child3)
1106 if tk_version >= (8, 7):
1107 self.nb.insert(2, child3)
1108 self.assertEqual(self.nb.tabs(), (*tabs, str(child3)))
1109 else:
1110 self.assertRaises(tkinter.TclError, self.nb.insert, 2, child3)
1111 self.assertRaises(tkinter.TclError, self.nb.insert, -1, child3)
1112
1113 # bad inserts
1114 self.assertRaises(tkinter.TclError, self.nb.insert, 'end', None)
1115 self.assertRaises(tkinter.TclError, self.nb.insert, None, 0)
1116 self.assertRaises(tkinter.TclError, self.nb.insert, None, None)
1117
1118 def test_select(self):
1119 self.nb.pack()
1120 self.nb.update()
1121
1122 success = []
1123 tab_changed = []
1124
1125 self.child1.bind('<Unmap>', lambda evt: success.append(True))
1126 self.nb.bind('<<NotebookTabChanged>>',
1127 lambda evt: tab_changed.append(True))
1128
1129 self.assertEqual(self.nb.select(), str(self.child1))
1130 self.nb.select(self.child2)
1131 self.assertTrue(success)
1132 self.assertEqual(self.nb.select(), str(self.child2))
1133
1134 self.nb.update()
1135 self.assertTrue(tab_changed)
1136
1137 def test_tab(self):
1138 self.assertRaises(tkinter.TclError, self.nb.tab, -1)
1139 self.assertRaises(tkinter.TclError, self.nb.tab, 'notab')
1140 self.assertRaises(tkinter.TclError, self.nb.tab, None)
1141
1142 self.assertIsInstance(self.nb.tab(self.child1), dict)
1143 self.assertEqual(self.nb.tab(self.child1, text=None), 'a')
1144 # newer form for querying a single option
1145 self.assertEqual(self.nb.tab(self.child1, 'text'), 'a')
1146 self.nb.tab(self.child1, text='abc')
1147 self.assertEqual(self.nb.tab(self.child1, text=None), 'abc')
1148 self.assertEqual(self.nb.tab(self.child1, 'text'), 'abc')
1149
1150 def test_configure_tabs(self):
1151 self.assertEqual(len(self.nb.tabs()), 2)
1152
1153 self.nb.forget(self.child1)
1154 self.nb.forget(self.child2)
1155
1156 self.assertEqual(self.nb.tabs(), ())
1157
1158 def test_traversal(self):
1159 self.nb.pack()
1160 self.nb.update()
1161
1162 self.nb.select(0)
1163
1164 focus_identify_as = 'focus' if sys.platform != 'darwin' else ''
1165 self.assertEqual(self.nb.identify(5, 5), focus_identify_as)
1166 simulate_mouse_click(self.nb, 5, 5)
1167 self.nb.focus_force()
1168 self.nb.event_generate('<Control-Tab>')
1169 self.assertEqual(self.nb.select(), str(self.child2))
1170 self.nb.focus_force()
1171 self.nb.event_generate('<Shift-Control-Tab>')
1172 self.assertEqual(self.nb.select(), str(self.child1))
1173 self.nb.focus_force()
1174 self.nb.event_generate('<Shift-Control-Tab>')
1175 self.assertEqual(self.nb.select(), str(self.child2))
1176
1177 self.nb.tab(self.child1, text='a', underline=0)
1178 self.nb.tab(self.child2, text='e', underline=0)
1179 self.nb.enable_traversal()
1180 self.nb.focus_force()
1181 self.assertEqual(self.nb.identify(5, 5), focus_identify_as)
1182 simulate_mouse_click(self.nb, 5, 5)
1183 # on macOS Emacs-style keyboard shortcuts are region-dependent;
1184 # let's use the regular arrow keys instead
1185 if sys.platform == 'darwin':
1186 begin = '<Left>'
1187 end = '<Right>'
1188 else:
1189 begin = '<Alt-a>'
1190 end = '<Alt-e>'
1191 self.nb.event_generate(begin)
1192 self.assertEqual(self.nb.select(), str(self.child1))
1193 self.nb.event_generate(end)
1194 self.assertEqual(self.nb.select(), str(self.child2))
1195
1196
1197 @add_standard_options(IntegerSizeTests, StandardTtkOptionsTests)
1198 class SpinboxTest(EntryTest, unittest.TestCase):
1199 OPTIONS = (
1200 'background', 'class', 'command', 'cursor', 'exportselection',
1201 'font', 'foreground', 'format', 'from', 'increment',
1202 'invalidcommand', 'justify',
1203 'placeholder', 'placeholderforeground',
1204 'show', 'state', 'style',
1205 'takefocus', 'textvariable', 'to', 'validate', 'validatecommand',
1206 'values', 'width', 'wrap', 'xscrollcommand',
1207 )
1208 IDENTIFY_AS = {'Spinbox.field', 'textarea'}
1209
1210 def setUp(self):
1211 super().setUp()
1212 self.spin = self.create()
1213 self.spin.pack()
1214
1215 def create(self, **kwargs):
1216 return ttk.Spinbox(self.root, **kwargs)
1217
1218 def _click_increment_arrow(self):
1219 width = self.spin.winfo_width()
1220 height = self.spin.winfo_height()
1221 x = width - 5
1222 y = height//2 - 5
1223 self.assertRegex(self.spin.identify(x, y), r'.*uparrow\Z')
1224 self.spin.event_generate('<ButtonPress-1>', x=x, y=y)
1225 self.spin.event_generate('<ButtonRelease-1>', x=x, y=y)
1226 self.spin.update_idletasks()
1227
1228 def _click_decrement_arrow(self):
1229 width = self.spin.winfo_width()
1230 height = self.spin.winfo_height()
1231 x = width - 5
1232 y = height//2 + 4
1233 self.assertRegex(self.spin.identify(x, y), r'.*downarrow\Z')
1234 self.spin.event_generate('<ButtonPress-1>', x=x, y=y)
1235 self.spin.event_generate('<ButtonRelease-1>', x=x, y=y)
1236 self.spin.update_idletasks()
1237
1238 def test_configure_command(self):
1239 success = []
1240
1241 self.spin['command'] = lambda: success.append(True)
1242 self.spin.update()
1243 self._click_increment_arrow()
1244 self.spin.update()
1245 self.assertTrue(success)
1246
1247 self._click_decrement_arrow()
1248 self.assertEqual(len(success), 2)
1249
1250 # testing postcommand removal
1251 self.spin['command'] = ''
1252 self.spin.update_idletasks()
1253 self._click_increment_arrow()
1254 self._click_decrement_arrow()
1255 self.spin.update()
1256 self.assertEqual(len(success), 2)
1257
1258 def test_configure_to(self):
1259 self.spin['from'] = 0
1260 self.spin['to'] = 5
1261 self.spin.set(4)
1262 self.spin.update()
1263 self._click_increment_arrow() # 5
1264
1265 self.assertEqual(self.spin.get(), '5')
1266
1267 self._click_increment_arrow() # 5
1268 self.assertEqual(self.spin.get(), '5')
1269
1270 def test_configure_from(self):
1271 self.spin['from'] = 1
1272 self.spin['to'] = 10
1273 self.spin.set(2)
1274 self.spin.update()
1275 self._click_decrement_arrow() # 1
1276 self.assertEqual(self.spin.get(), '1')
1277 self._click_decrement_arrow() # 1
1278 self.assertEqual(self.spin.get(), '1')
1279
1280 def test_configure_increment(self):
1281 self.spin['from'] = 0
1282 self.spin['to'] = 10
1283 self.spin['increment'] = 4
1284 self.spin.set(1)
1285 self.spin.update()
1286
1287 self._click_increment_arrow() # 5
1288 self.assertEqual(self.spin.get(), '5')
1289 self.spin['increment'] = 2
1290 self.spin.update()
1291 self._click_decrement_arrow() # 3
1292 self.assertEqual(self.spin.get(), '3')
1293
1294 def test_configure_format(self):
1295 self.spin.set(1)
1296 self.spin['format'] = '%10.3f'
1297 self.spin.update()
1298 self._click_increment_arrow()
1299 value = self.spin.get()
1300
1301 self.assertEqual(len(value), 10)
1302 self.assertEqual(value.index('.'), 6)
1303
1304 self.spin['format'] = ''
1305 self.spin.update()
1306 self._click_increment_arrow()
1307 value = self.spin.get()
1308 self.assertTrue('.' not in value)
1309 self.assertEqual(len(value), 1)
1310
1311 def test_configure_wrap(self):
1312 self.spin['to'] = 10
1313 self.spin['from'] = 1
1314 self.spin.set(1)
1315 self.spin['wrap'] = True
1316 self.spin.update()
1317
1318 self._click_decrement_arrow()
1319 self.assertEqual(self.spin.get(), '10')
1320
1321 self._click_increment_arrow()
1322 self.assertEqual(self.spin.get(), '1')
1323
1324 self.spin['wrap'] = False
1325 self.spin.update()
1326
1327 self._click_decrement_arrow()
1328 self.assertEqual(self.spin.get(), '1')
1329
1330 def test_configure_values(self):
1331 self.assertEqual(self.spin['values'], '')
1332 self.checkParam(self.spin, 'values', 'mon tue wed thur',
1333 expected=('mon', 'tue', 'wed', 'thur'))
1334 self.checkParam(self.spin, 'values', ('mon', 'tue', 'wed', 'thur'))
1335 self.checkParam(self.spin, 'values', (42, 3.14, '', 'any string'))
1336 self.checkParam(self.spin, 'values', '')
1337
1338 self.spin['values'] = ['a', 1, 'c']
1339
1340 # test incrementing / decrementing values
1341 self.spin.set('a')
1342 self.spin.update()
1343 self._click_increment_arrow()
1344 self.assertEqual(self.spin.get(), '1')
1345
1346 self._click_decrement_arrow()
1347 self.assertEqual(self.spin.get(), 'a')
1348
1349 # testing values with empty string set through configure
1350 self.spin.configure(values=[1, '', 2])
1351 self.assertEqual(self.spin['values'],
1352 ('1', '', '2') if self.wantobjects else
1353 '1 {} 2')
1354
1355 # testing values with spaces
1356 self.spin['values'] = ['a b', 'a\tb', 'a\nb']
1357 self.assertEqual(self.spin['values'],
1358 ('a b', 'a\tb', 'a\nb') if self.wantobjects else
1359 '{a b} {a\tb} {a\nb}')
1360
1361 # testing values with special characters
1362 self.spin['values'] = [r'a\tb', '"a"', '} {']
1363 self.assertEqual(self.spin['values'],
1364 (r'a\tb', '"a"', '} {') if self.wantobjects else
1365 r'a\\tb {"a"} \}\ \{')
1366
1367 # testing creating spinbox with empty string in values
1368 spin2 = ttk.Spinbox(self.root, values=[1, 2, ''])
1369 self.assertEqual(spin2['values'],
1370 ('1', '2', '') if self.wantobjects else '1 2 {}')
1371 spin2.destroy()
1372
1373
1374 @add_standard_options(StandardTtkOptionsTests)
1375 class TreeviewTest(AbstractWidgetTest, unittest.TestCase):
1376 OPTIONS = (
1377 'class', 'columns', 'cursor', 'displaycolumns',
1378 'height', 'padding', 'selectmode', 'selecttype', 'show', 'striped',
1379 'style', 'takefocus', 'titlecolumns', 'titleitems',
1380 'xscrollcommand', 'yscrollcommand',
1381 )
1382
1383 def setUp(self):
1384 super().setUp()
1385 self.tv = self.create(padding=0)
1386
1387 def create(self, **kwargs):
1388 return ttk.Treeview(self.root, **kwargs)
1389
1390 def test_configure_columns(self):
1391 widget = self.create()
1392 self.checkParam(widget, 'columns', 'a b c',
1393 expected=('a', 'b', 'c'))
1394 self.checkParam(widget, 'columns', ('a', 'b', 'c'))
1395 self.checkParam(widget, 'columns', '',
1396 expected=() if tk_version >= (8, 7) else '')
1397
1398 def test_configure_displaycolumns(self):
1399 widget = self.create()
1400 widget['columns'] = ('a', 'b', 'c')
1401 self.checkParam(widget, 'displaycolumns', 'b a c',
1402 expected=('b', 'a', 'c'))
1403 self.checkParam(widget, 'displaycolumns', ('b', 'a', 'c'))
1404 self.checkParam(widget, 'displaycolumns', '#all',
1405 expected=('#all',))
1406 self.checkParam(widget, 'displaycolumns', (2, 1, 0))
1407 self.checkInvalidParam(widget, 'displaycolumns', ('a', 'b', 'd'),
1408 errmsg='Invalid column index "?d"?')
1409 errmsg = 'Column index "?{}"? out of bounds'
1410 self.checkInvalidParam(widget, 'displaycolumns', (1, 2, 3),
1411 errmsg=errmsg.format(3))
1412 self.checkInvalidParam(widget, 'displaycolumns', (1, -2),
1413 errmsg=errmsg.format(-2))
1414
1415 def test_configure_height(self):
1416 widget = self.create()
1417 self.checkPixelsParam(widget, 'height', 100, -100, 0, '3c', conv=False)
1418 self.checkPixelsParam(widget, 'height', 101.2, 102.6, conv=False)
1419
1420 def test_configure_selectmode(self):
1421 widget = self.create()
1422 self.checkEnumParam(widget, 'selectmode',
1423 'none', 'browse', 'extended')
1424
1425 @requires_tk(8, 7)
1426 def test_configure_selecttype(self):
1427 widget = self.create()
1428 self.checkEnumParam(widget, 'selecttype', 'item', 'cell')
1429
1430 def test_configure_show(self):
1431 widget = self.create()
1432 self.checkParam(widget, 'show', 'tree headings',
1433 expected=('tree', 'headings'))
1434 self.checkParam(widget, 'show', ('tree', 'headings'))
1435 self.checkParam(widget, 'show', ('headings', 'tree'))
1436 self.checkParam(widget, 'show', 'tree', expected=('tree',))
1437 self.checkParam(widget, 'show', 'headings', expected=('headings',))
1438
1439 @requires_tk(8, 7)
1440 def test_configure_striped(self):
1441 widget = self.create()
1442 self.checkBooleanParam(widget, 'striped')
1443
1444 @requires_tk(8, 7)
1445 def test_configure_titlecolumns(self):
1446 widget = self.create()
1447 self.checkIntegerParam(widget, 'titlecolumns', 0, 1, 5)
1448 self.checkInvalidParam(widget, 'titlecolumns', -2)
1449
1450 @requires_tk(8, 7)
1451 def test_configure_titleitems(self):
1452 widget = self.create()
1453 self.checkIntegerParam(widget, 'titleitems', 0, 1, 5)
1454 self.checkInvalidParam(widget, 'titleitems', -2)
1455
1456 def test_bbox(self):
1457 self.tv.pack()
1458 self.assertEqual(self.tv.bbox(''), '')
1459 self.tv.update()
1460
1461 item_id = self.tv.insert('', 'end')
1462 children = self.tv.get_children()
1463 self.assertTrue(children)
1464
1465 bbox = self.tv.bbox(children[0])
1466 self.assertIsBoundingBox(bbox)
1467
1468 # compare width in bboxes
1469 self.tv['columns'] = ['test']
1470 self.tv.column('test', width=50)
1471 bbox_column0 = self.tv.bbox(children[0], 0)
1472 root_width = self.tv.column('#0', width=None)
1473 if not self.wantobjects:
1474 root_width = int(root_width)
1475 self.assertEqual(bbox_column0[0], bbox[0] + root_width)
1476
1477 # verify that bbox of a closed item is the empty string
1478 child1 = self.tv.insert(item_id, 'end')
1479 self.assertEqual(self.tv.bbox(child1), '')
1480
1481 def test_children(self):
1482 # no children yet, should get an empty tuple
1483 self.assertEqual(self.tv.get_children(), ())
1484
1485 item_id = self.tv.insert('', 'end')
1486 self.assertIsInstance(self.tv.get_children(), tuple)
1487 self.assertEqual(self.tv.get_children()[0], item_id)
1488
1489 # add item_id and child3 as children of child2
1490 child2 = self.tv.insert('', 'end')
1491 child3 = self.tv.insert('', 'end')
1492 self.tv.set_children(child2, item_id, child3)
1493 self.assertEqual(self.tv.get_children(child2), (item_id, child3))
1494
1495 # child3 has child2 as parent, thus trying to set child2 as a children
1496 # of child3 should result in an error
1497 self.assertRaises(tkinter.TclError,
1498 self.tv.set_children, child3, child2)
1499
1500 # remove child2 children
1501 self.tv.set_children(child2)
1502 self.assertEqual(self.tv.get_children(child2), ())
1503
1504 # remove root's children
1505 self.tv.set_children('')
1506 self.assertEqual(self.tv.get_children(), ())
1507
1508 def test_column(self):
1509 # return a dict with all options/values
1510 self.assertIsInstance(self.tv.column('#0'), dict)
1511 # return a single value of the given option
1512 if self.wantobjects:
1513 self.assertIsInstance(self.tv.column('#0', width=None), int)
1514 # set a new value for an option
1515 self.tv.column('#0', width=10)
1516 # testing new way to get option value
1517 self.assertEqual(self.tv.column('#0', 'width'),
1518 10 if self.wantobjects else '10')
1519 self.assertEqual(self.tv.column('#0', width=None),
1520 10 if self.wantobjects else '10')
1521 # check read-only option
1522 self.assertRaises(tkinter.TclError, self.tv.column, '#0', id='X')
1523
1524 self.assertRaises(tkinter.TclError, self.tv.column, 'invalid')
1525 invalid_kws = [
1526 {'unknown_option': 'some value'}, {'stretch': 'wrong'},
1527 {'anchor': 'wrong'}, {'width': 'wrong'}, {'minwidth': 'wrong'}
1528 ]
1529 for kw in invalid_kws:
1530 self.assertRaises(tkinter.TclError, self.tv.column, '#0',
1531 **kw)
1532
1533 def test_delete(self):
1534 self.assertRaises(tkinter.TclError, self.tv.delete, '#0')
1535
1536 item_id = self.tv.insert('', 'end')
1537 item2 = self.tv.insert(item_id, 'end')
1538 self.assertEqual(self.tv.get_children(), (item_id, ))
1539 self.assertEqual(self.tv.get_children(item_id), (item2, ))
1540
1541 self.tv.delete(item_id)
1542 self.assertFalse(self.tv.get_children())
1543
1544 # reattach should fail
1545 self.assertRaises(tkinter.TclError,
1546 self.tv.reattach, item_id, '', 'end')
1547
1548 # test multiple item delete
1549 item1 = self.tv.insert('', 'end')
1550 item2 = self.tv.insert('', 'end')
1551 self.assertEqual(self.tv.get_children(), (item1, item2))
1552
1553 self.tv.delete(item1, item2)
1554 self.assertFalse(self.tv.get_children())
1555
1556 def test_detach_reattach(self):
1557 item_id = self.tv.insert('', 'end')
1558 item2 = self.tv.insert(item_id, 'end')
1559
1560 # calling detach without items is valid, although it does nothing
1561 prev = self.tv.get_children()
1562 self.tv.detach() # this should do nothing
1563 self.assertEqual(prev, self.tv.get_children())
1564
1565 self.assertEqual(self.tv.get_children(), (item_id, ))
1566 self.assertEqual(self.tv.get_children(item_id), (item2, ))
1567
1568 # detach item with children
1569 self.tv.detach(item_id)
1570 self.assertFalse(self.tv.get_children())
1571
1572 # reattach item with children
1573 self.tv.reattach(item_id, '', 'end')
1574 self.assertEqual(self.tv.get_children(), (item_id, ))
1575 self.assertEqual(self.tv.get_children(item_id), (item2, ))
1576
1577 # move a children to the root
1578 self.tv.move(item2, '', 'end')
1579 self.assertEqual(self.tv.get_children(), (item_id, item2))
1580 self.assertEqual(self.tv.get_children(item_id), ())
1581
1582 # bad values
1583 self.assertRaises(tkinter.TclError,
1584 self.tv.reattach, 'nonexistent', '', 'end')
1585 self.assertRaises(tkinter.TclError,
1586 self.tv.detach, 'nonexistent')
1587 self.assertRaises(tkinter.TclError,
1588 self.tv.reattach, item2, 'otherparent', 'end')
1589 self.assertRaises(tkinter.TclError,
1590 self.tv.reattach, item2, '', 'invalid')
1591
1592 # multiple detach
1593 self.tv.detach(item_id, item2)
1594 self.assertEqual(self.tv.get_children(), ())
1595 self.assertEqual(self.tv.get_children(item_id), ())
1596
1597 def test_exists(self):
1598 self.assertEqual(self.tv.exists('something'), False)
1599 self.assertEqual(self.tv.exists(''), True)
1600 self.assertEqual(self.tv.exists({}), False)
1601
1602 # the following will make a tk.call equivalent to
1603 # tk.call(treeview, "exists") which should result in an error
1604 # in the tcl interpreter since tk requires an item.
1605 self.assertRaises(tkinter.TclError, self.tv.exists, None)
1606
1607 def test_focus(self):
1608 # nothing is focused right now
1609 self.assertEqual(self.tv.focus(), '')
1610
1611 item1 = self.tv.insert('', 'end')
1612 self.tv.focus(item1)
1613 self.assertEqual(self.tv.focus(), item1)
1614
1615 self.tv.delete(item1)
1616 self.assertEqual(self.tv.focus(), '')
1617
1618 # try focusing inexistent item
1619 self.assertRaises(tkinter.TclError, self.tv.focus, 'hi')
1620
1621 def test_heading(self):
1622 # check a dict is returned
1623 self.assertIsInstance(self.tv.heading('#0'), dict)
1624
1625 # check a value is returned
1626 self.tv.heading('#0', text='hi')
1627 self.assertEqual(self.tv.heading('#0', 'text'), 'hi')
1628 self.assertEqual(self.tv.heading('#0', text=None), 'hi')
1629
1630 # invalid option
1631 self.assertRaises(tkinter.TclError, self.tv.heading, '#0',
1632 background=None)
1633 # invalid value
1634 self.assertRaises(tkinter.TclError, self.tv.heading, '#0',
1635 anchor=1)
1636
1637 def test_heading_callback(self):
1638 def simulate_heading_click(x, y):
1639 if tk_version >= (8, 6):
1640 self.assertEqual(self.tv.identify_column(x), '#0')
1641 self.assertEqual(self.tv.identify_region(x, y), 'heading')
1642 simulate_mouse_click(self.tv, x, y)
1643 self.tv.update()
1644
1645 success = [] # no success for now
1646
1647 self.tv.pack()
1648 self.tv.heading('#0', command=lambda: success.append(True))
1649 self.tv.column('#0', width=100)
1650 self.tv.update()
1651
1652 # assuming that the coords (5, 5) fall into heading #0
1653 simulate_heading_click(5, 5)
1654 if not success:
1655 self.fail("The command associated to the treeview heading wasn't "
1656 "invoked.")
1657
1658 success = []
1659 commands = self.tv.master._tclCommands
1660 self.tv.heading('#0', command=str(self.tv.heading('#0', command=None)))
1661 self.assertEqual(commands, self.tv.master._tclCommands)
1662 simulate_heading_click(5, 5)
1663 if not success:
1664 self.fail("The command associated to the treeview heading wasn't "
1665 "invoked.")
1666
1667 # XXX The following raises an error in a tcl interpreter, but not in
1668 # Python
1669 #self.tv.heading('#0', command='I dont exist')
1670 #simulate_heading_click(5, 5)
1671
1672 def test_index(self):
1673 # item 'what' doesn't exist
1674 self.assertRaises(tkinter.TclError, self.tv.index, 'what')
1675
1676 self.assertEqual(self.tv.index(''), 0)
1677
1678 item1 = self.tv.insert('', 'end')
1679 item2 = self.tv.insert('', 'end')
1680 c1 = self.tv.insert(item1, 'end')
1681 c2 = self.tv.insert(item1, 'end')
1682 self.assertEqual(self.tv.index(item1), 0)
1683 self.assertEqual(self.tv.index(c1), 0)
1684 self.assertEqual(self.tv.index(c2), 1)
1685 self.assertEqual(self.tv.index(item2), 1)
1686
1687 self.tv.move(item2, '', 0)
1688 self.assertEqual(self.tv.index(item2), 0)
1689 self.assertEqual(self.tv.index(item1), 1)
1690
1691 # check that index still works even after its parent and siblings
1692 # have been detached
1693 self.tv.detach(item1)
1694 self.assertEqual(self.tv.index(c2), 1)
1695 self.tv.detach(c1)
1696 self.assertEqual(self.tv.index(c2), 0)
1697
1698 # but it fails after item has been deleted
1699 self.tv.delete(item1)
1700 self.assertRaises(tkinter.TclError, self.tv.index, c2)
1701
1702 def test_insert_item(self):
1703 # parent 'none' doesn't exist
1704 self.assertRaises(tkinter.TclError, self.tv.insert, 'none', 'end')
1705
1706 # open values
1707 self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end',
1708 open='')
1709 self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end',
1710 open='please')
1711 self.assertFalse(self.tv.delete(self.tv.insert('', 'end', open=True)))
1712 self.assertFalse(self.tv.delete(self.tv.insert('', 'end', open=False)))
1713
1714 # invalid index
1715 self.assertRaises(tkinter.TclError, self.tv.insert, '', 'middle')
1716
1717 # trying to duplicate item id is invalid
1718 itemid = self.tv.insert('', 'end', 'first-item')
1719 self.assertEqual(itemid, 'first-item')
1720 self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end',
1721 'first-item')
1722 self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end',
1723 MockTclObj('first-item'))
1724
1725 # unicode values
1726 value = '\xe1ba'
1727 item = self.tv.insert('', 'end', values=(value, ))
1728 self.assertEqual(self.tv.item(item, 'values'),
1729 (value,) if self.wantobjects else value)
1730 self.assertEqual(self.tv.item(item, values=None),
1731 (value,) if self.wantobjects else value)
1732
1733 self.tv.item(item, values=self.root.splitlist(self.tv.item(item, values=None)))
1734 self.assertEqual(self.tv.item(item, values=None),
1735 (value,) if self.wantobjects else value)
1736
1737 self.assertIsInstance(self.tv.item(item), dict)
1738
1739 # erase item values
1740 self.tv.item(item, values='')
1741 self.assertFalse(self.tv.item(item, values=None))
1742
1743 # item tags
1744 item = self.tv.insert('', 'end', tags=[1, 2, value])
1745 self.assertEqual(self.tv.item(item, tags=None),
1746 ('1', '2', value) if self.wantobjects else
1747 '1 2 %s' % value)
1748 self.tv.item(item, tags=[])
1749 self.assertFalse(self.tv.item(item, tags=None))
1750 self.tv.item(item, tags=(1, 2))
1751 self.assertEqual(self.tv.item(item, tags=None),
1752 ('1', '2') if self.wantobjects else '1 2')
1753
1754 # values with spaces
1755 item = self.tv.insert('', 'end', values=('a b c',
1756 '%s %s' % (value, value)))
1757 self.assertEqual(self.tv.item(item, values=None),
1758 ('a b c', '%s %s' % (value, value)) if self.wantobjects else
1759 '{a b c} {%s %s}' % (value, value))
1760
1761 # text
1762 self.assertEqual(self.tv.item(
1763 self.tv.insert('', 'end', text="Label here"), text=None),
1764 "Label here")
1765 self.assertEqual(self.tv.item(
1766 self.tv.insert('', 'end', text=value), text=None),
1767 value)
1768
1769 # test for values which are not None
1770 itemid = self.tv.insert('', 'end', 0)
1771 self.assertEqual(itemid, '0')
1772 itemid = self.tv.insert('', 'end', 0.0)
1773 self.assertEqual(itemid, '0.0')
1774 # this is because False resolves to 0 and element with 0 iid is already present
1775 self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end', False)
1776 self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end', '')
1777
1778 def test_selection(self):
1779 self.assertRaises(TypeError, self.tv.selection, 'spam')
1780 # item 'none' doesn't exist
1781 self.assertRaises(tkinter.TclError, self.tv.selection_set, 'none')
1782 self.assertRaises(tkinter.TclError, self.tv.selection_add, 'none')
1783 self.assertRaises(tkinter.TclError, self.tv.selection_remove, 'none')
1784 self.assertRaises(tkinter.TclError, self.tv.selection_toggle, 'none')
1785
1786 item1 = self.tv.insert('', 'end')
1787 item2 = self.tv.insert('', 'end')
1788 c1 = self.tv.insert(item1, 'end')
1789 c2 = self.tv.insert(item1, 'end')
1790 c3 = self.tv.insert(item1, 'end')
1791 self.assertEqual(self.tv.selection(), ())
1792
1793 self.tv.selection_set(c1, item2)
1794 self.assertEqual(self.tv.selection(), (c1, item2))
1795 self.tv.selection_set(c2)
1796 self.assertEqual(self.tv.selection(), (c2,))
1797
1798 self.tv.selection_add(c1, item2)
1799 self.assertEqual(self.tv.selection(), (c1, c2, item2))
1800 self.tv.selection_add(item1)
1801 self.assertEqual(self.tv.selection(), (item1, c1, c2, item2))
1802 self.tv.selection_add()
1803 self.assertEqual(self.tv.selection(), (item1, c1, c2, item2))
1804
1805 self.tv.selection_remove(item1, c3)
1806 self.assertEqual(self.tv.selection(), (c1, c2, item2))
1807 self.tv.selection_remove(c2)
1808 self.assertEqual(self.tv.selection(), (c1, item2))
1809 self.tv.selection_remove()
1810 self.assertEqual(self.tv.selection(), (c1, item2))
1811
1812 self.tv.selection_toggle(c1, c3)
1813 self.assertEqual(self.tv.selection(), (c3, item2))
1814 self.tv.selection_toggle(item2)
1815 self.assertEqual(self.tv.selection(), (c3,))
1816 self.tv.selection_toggle()
1817 self.assertEqual(self.tv.selection(), (c3,))
1818
1819 self.tv.insert('', 'end', id='with spaces')
1820 self.tv.selection_set('with spaces')
1821 self.assertEqual(self.tv.selection(), ('with spaces',))
1822
1823 self.tv.insert('', 'end', id='{brace')
1824 self.tv.selection_set('{brace')
1825 self.assertEqual(self.tv.selection(), ('{brace',))
1826
1827 self.tv.insert('', 'end', id='unicode\u20ac')
1828 self.tv.selection_set('unicode\u20ac')
1829 self.assertEqual(self.tv.selection(), ('unicode\u20ac',))
1830
1831 self.tv.insert('', 'end', id=b'bytes\xe2\x82\xac')
1832 self.tv.selection_set(b'bytes\xe2\x82\xac')
1833 self.assertEqual(self.tv.selection(), ('bytes\xe2\x82\xac',))
1834
1835 self.tv.selection_set()
1836 self.assertEqual(self.tv.selection(), ())
1837
1838 # Old interface
1839 self.tv.selection_set((c1, item2))
1840 self.assertEqual(self.tv.selection(), (c1, item2))
1841 self.tv.selection_add((c1, item1))
1842 self.assertEqual(self.tv.selection(), (item1, c1, item2))
1843 self.tv.selection_remove((item1, c3))
1844 self.assertEqual(self.tv.selection(), (c1, item2))
1845 self.tv.selection_toggle((c1, c3))
1846 self.assertEqual(self.tv.selection(), (c3, item2))
1847
1848 def test_set(self):
1849 self.tv['columns'] = ['A', 'B']
1850 item = self.tv.insert('', 'end', values=['a', 'b'])
1851 self.assertEqual(self.tv.set(item), {'A': 'a', 'B': 'b'})
1852
1853 self.tv.set(item, 'B', 'a')
1854 self.assertEqual(self.tv.item(item, values=None),
1855 ('a', 'a') if self.wantobjects else 'a a')
1856
1857 self.tv['columns'] = ['B']
1858 self.assertEqual(self.tv.set(item), {'B': 'a'})
1859
1860 self.tv.set(item, 'B', 'b')
1861 self.assertEqual(self.tv.set(item, column='B'), 'b')
1862 self.assertEqual(self.tv.item(item, values=None),
1863 ('b', 'a') if self.wantobjects else 'b a')
1864
1865 self.tv.set(item, 'B', 123)
1866 self.assertEqual(self.tv.set(item, 'B'),
1867 123 if self.wantobjects else '123')
1868 self.assertEqual(self.tv.item(item, values=None),
1869 (123, 'a') if self.wantobjects else '123 a')
1870 self.assertEqual(self.tv.set(item),
1871 {'B': 123} if self.wantobjects else {'B': '123'})
1872
1873 # inexistent column
1874 self.assertRaises(tkinter.TclError, self.tv.set, item, 'A')
1875 self.assertRaises(tkinter.TclError, self.tv.set, item, 'A', 'b')
1876
1877 # inexistent item
1878 self.assertRaises(tkinter.TclError, self.tv.set, 'notme')
1879
1880 def test_tag_bind(self):
1881 events = []
1882 item1 = self.tv.insert('', 'end', tags=['call'])
1883 item2 = self.tv.insert('', 'end', tags=['call'])
1884 self.tv.tag_bind('call', '<ButtonPress-1>',
1885 lambda evt: events.append(1))
1886 self.tv.tag_bind('call', '<ButtonRelease-1>',
1887 lambda evt: events.append(2))
1888
1889 self.tv.pack()
1890 self.tv.update()
1891
1892 pos_y = set()
1893 found = set()
1894 for i in range(0, 100, 10):
1895 if len(found) == 2: # item1 and item2 already found
1896 break
1897 item_id = self.tv.identify_row(i)
1898 if item_id and item_id not in found:
1899 pos_y.add(i)
1900 found.add(item_id)
1901
1902 self.assertEqual(len(pos_y), 2) # item1 and item2 y pos
1903 for y in pos_y:
1904 simulate_mouse_click(self.tv, 0, y)
1905
1906 # by now there should be 4 things in the events list, since each
1907 # item had a bind for two events that were simulated above
1908 self.assertEqual(len(events), 4)
1909 for evt in zip(events[::2], events[1::2]):
1910 self.assertEqual(evt, (1, 2))
1911
1912 def test_tag_configure(self):
1913 # Just testing parameter passing for now
1914 self.assertRaises(TypeError, self.tv.tag_configure)
1915 self.assertRaises(tkinter.TclError, self.tv.tag_configure,
1916 'test', sky='blue')
1917 self.tv.tag_configure('test', foreground='blue')
1918 self.assertEqual(str(self.tv.tag_configure('test', 'foreground')),
1919 'blue')
1920 self.assertEqual(str(self.tv.tag_configure('test', foreground=None)),
1921 'blue')
1922 self.assertIsInstance(self.tv.tag_configure('test'), dict)
1923
1924 def test_tag_has(self):
1925 item1 = self.tv.insert('', 'end', text='Item 1', tags=['tag1'])
1926 item2 = self.tv.insert('', 'end', text='Item 2', tags=['tag2'])
1927 self.assertRaises(TypeError, self.tv.tag_has)
1928 self.assertRaises(TclError, self.tv.tag_has, 'tag1', 'non-existing')
1929 self.assertTrue(self.tv.tag_has('tag1', item1))
1930 self.assertFalse(self.tv.tag_has('tag1', item2))
1931 self.assertFalse(self.tv.tag_has('tag2', item1))
1932 self.assertTrue(self.tv.tag_has('tag2', item2))
1933 self.assertFalse(self.tv.tag_has('tag3', item1))
1934 self.assertFalse(self.tv.tag_has('tag3', item2))
1935 self.assertEqual(self.tv.tag_has('tag1'), (item1,))
1936 self.assertEqual(self.tv.tag_has('tag2'), (item2,))
1937 self.assertEqual(self.tv.tag_has('tag3'), ())
1938
1939
1940 @add_standard_options(StandardTtkOptionsTests)
1941 class SeparatorTest(AbstractWidgetTest, unittest.TestCase):
1942 OPTIONS = (
1943 'class', 'cursor', 'orient', 'style', 'takefocus',
1944 # 'state'?
1945 )
1946 default_orient = 'horizontal'
1947
1948 def create(self, **kwargs):
1949 return ttk.Separator(self.root, **kwargs)
1950
1951
1952 @add_standard_options(StandardTtkOptionsTests)
1953 class SizegripTest(AbstractWidgetTest, unittest.TestCase):
1954 OPTIONS = (
1955 'class', 'cursor', 'style', 'takefocus',
1956 # 'state'?
1957 )
1958
1959 def create(self, **kwargs):
1960 return ttk.Sizegrip(self.root, **kwargs)
1961
1962
1963 class DefaultRootTest(AbstractDefaultRootTest, unittest.TestCase):
1964
1965 def test_frame(self):
1966 self._test_widget(ttk.Frame)
1967
1968 def test_label(self):
1969 self._test_widget(ttk.Label)
1970
1971
1972 if __name__ == "__main__":
1973 unittest.main()