File: Tabular_editor_with_context_menu_demo.py

package info (click to toggle)
python-traitsui 8.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 18,232 kB
  • sloc: python: 58,982; makefile: 113
file content (197 lines) | stat: -rw-r--r-- 5,613 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# (C) Copyright 2004-2023 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
#
# Thanks for using Enthought open source!

"""
**WARNING**

  This demo might not work as expected and some documented features might be
  missing.

-------------------------------------------------------------------------------

Defining column-specific context menu in a Tabular Editor. Shows how the
example for the Table Editor (`Table_Editor_with_context_menu_demo.py`) can be
adapted to work with a Tabular Editor.

The demo is a simple baseball scoring system, which lists each player and
their current batting statistics. After a given player has an at bat, you
right-click on the table cell corresponding to the player and the result of
the at-bat (e.g. 'S' = single) and select the 'Add' menu option to register
that the player hit a single and update the player's overall statistics.

This demo also illustrates the use of Property traits, and how using 'event'
meta-data can simplify event handling by collapsing an event that can
occur on a number of traits into a category of event, which can be handled by
a single event handler defined for the category (in this case, the category
is 'affects_average').
"""
# Issue related to the demo warning: enthought/traitsui#960


from random import randint
from traits.api import HasStrictTraits, Str, Int, Float, List, Property
from traitsui.api import (
    Action,
    Item,
    Menu,
    TabularAdapter,
    TabularEditor,
    View,
)


# Define a custom tabular adapter for handling items which affect the player's
# batting average:
class PlayerAdapter(TabularAdapter):

    # Overwrite default values
    alignment = 'center'
    width = 0.09

    def get_menu(self, object, trait, row, column):
        column_name = self.column_map[column]
        if column_name not in ['name', 'average']:
            menu = Menu(
                Action(name='Add', action='editor.adapter.add(item, column)'),
                Action(name='Sub', action='editor.adapter.sub(item, column)'),
            )
            return menu
        else:
            return super().get_menu(object, trait, row, column)

    def get_format(self, object, trait, row, column):
        column_name = self.column_map[column]
        if column_name == 'average':
            return '%0.3f'
        else:
            return super().get_format(object, trait, row, column)

    def add(self, object, column):
        """Increment the affected player statistic."""
        column_name = self.column_map[column]
        setattr(object, column_name, getattr(object, column_name) + 1)

    def sub(self, object, column):
        """Decrement the affected player statistic."""
        column_name = self.column_map[column]
        setattr(object, column_name, getattr(object, column_name) - 1)


# The 'players' trait table editor:
columns = [
    ('Player Name', 'name'),
    ('AB', 'at_bats'),
    ('SO', 'strike_outs'),
    ('S', 'singles'),
    ('D', 'doubles'),
    ('T', 'triples'),
    ('HR', 'home_runs'),
    ('W', 'walks'),
    ('Ave', 'average'),
]

player_editor = TabularEditor(
    editable=True,
    auto_resize=True,
    auto_resize_rows=True,
    stretch_last_section=False,
    auto_update=True,
    adapter=PlayerAdapter(columns=columns),
)


# 'Player' class:
class Player(HasStrictTraits):

    # Trait definitions:
    name = Str()
    at_bats = Int()
    strike_outs = Int(event='affects_average')
    singles = Int(event='affects_average')
    doubles = Int(event='affects_average')
    triples = Int(event='affects_average')
    home_runs = Int(event='affects_average')
    walks = Int()
    average = Property(Float)

    def _get_average(self):
        """Computes the player's batting average from the current statistics."""
        if self.at_bats == 0:
            return 0.0

        return (
            float(self.singles + self.doubles + self.triples + self.home_runs)
            / self.at_bats
        )

    def _affects_average_changed(self):
        """Handles an event that affects the player's batting average."""
        self.at_bats += 1


class Team(HasStrictTraits):

    # Trait definitions:
    players = List(Player)

    # Trait view definitions:
    traits_view = View(
        Item('players', show_label=False, editor=player_editor),
        title='Baseball Scoring Demo',
        width=0.5,
        height=0.5,
        resizable=True,
    )


def random_player(name):
    """Generates and returns a random player."""
    p = Player(
        name=name,
        strike_outs=randint(0, 50),
        singles=randint(0, 50),
        doubles=randint(0, 20),
        triples=randint(0, 5),
        home_runs=randint(0, 30),
        walks=randint(0, 50),
    )
    return p.trait_set(
        at_bats=(
            p.strike_outs
            + p.singles
            + p.doubles
            + p.triples
            + p.home_runs
            + randint(100, 200)
        )
    )


# Create the demo:
demo = Team(
    players=[
        random_player(name)
        for name in [
            'Dave',
            'Mike',
            'Joe',
            'Tom',
            'Dick',
            'Harry',
            'Dirk',
            'Fields',
            'Stretch',
        ]
    ]
)

# Run the demo (if invoked from the command line):
if __name__ == '__main__':
    demo.configure_traits()