Coverage for ase/gui/widgets.py: 77.42%

62 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1import ase.data 

2import ase.gui.ui as ui 

3from ase import Atoms 

4from ase.gui.i18n import _ 

5 

6 

7class Element(list): 

8 def __init__(self, symbol='', callback=None): 

9 list.__init__( 

10 self, 

11 [ 

12 _('Element:'), 

13 ui.Entry(symbol, 3, self.enter), 

14 ui.Button(_('Help'), self.show_help), 

15 ui.Label('', 'red'), 

16 ], 

17 ) 

18 self.callback = callback 

19 

20 @property 

21 def z_entry(self): 

22 return self[1] 

23 

24 def grab_focus(self): 

25 self.z_entry.entry.focus_set() 

26 

27 def show_help(self): 

28 msg = _('Enter a chemical symbol or the atomic number.') 

29 # Title of a popup window 

30 ui.showinfo(_('Info'), msg) 

31 

32 @property 

33 def Z(self): 

34 atoms = self.get_atoms() 

35 if atoms is None: 

36 return None 

37 assert len(atoms) == 1 

38 return atoms.numbers[0] 

39 

40 @property 

41 def symbol(self): 

42 Z = self.Z 

43 return None if Z is None else ase.data.chemical_symbols[Z] 

44 

45 # Used by tests... 

46 @symbol.setter 

47 def symbol(self, value): 

48 self.z_entry.value = value 

49 

50 def get_atoms(self): 

51 val = self._get() 

52 if val is not None: 

53 self[2].text = '' 

54 return val 

55 

56 def _get(self): 

57 txt = self.z_entry.value 

58 

59 if not txt: 

60 self.error(_('No element specified!')) 

61 return None 

62 

63 if txt.isdigit(): 

64 txt = int(txt) 

65 try: 

66 txt = ase.data.chemical_symbols[txt] 

67 except KeyError: 

68 self.error() 

69 return None 

70 

71 if txt in ase.data.atomic_numbers: 

72 return Atoms(txt) 

73 

74 self.error() 

75 

76 def enter(self): 

77 self.callback(self) 

78 

79 def error(self, text=_('ERROR: Invalid element!')): 

80 self[2].text = text 

81 

82 

83def pybutton(title, callback): 

84 """A button for displaying Python code. 

85 

86 When pressed, it opens a window displaying some Python code, or an error 

87 message if no Python code is ready. 

88 """ 

89 return ui.Button('Python', pywindow, title, callback) 

90 

91 

92def pywindow(title, callback): 

93 code = callback() 

94 if code is None: 

95 ui.error( 

96 _('No Python code'), 

97 _('You have not (yet) specified a consistent set of parameters.'), 

98 ) 

99 else: 

100 win = ui.Window(title) 

101 win.add(ui.Text(code))