gui design question
I use tkinter, but my question is probably general.
This is the first time I'm designing GUI. Each of my objects is modeled as a class. I don't understand how to tie the GUI class hierarchy with the rest of the class hierarchy.
For example, I have creatures:开发者_StackOverflow中文版
# this is before I had any GUI in my code
class Creature:
def current_position() # returns real-time x, y coords
# ...
I want to display them as circles that move around on a canvas. It seemed reasonable to me that the graphical representation of movement should be provided by a method update_display
in class Creature
. However, that means that class Creature
has to know the details about the GUI. In addition, the class App(tkinter.Tk)
with a redraw
method would need to know the list of all existing Creature
instances in order to call their update_display
methods. That's way too much dependency.
What's the right approach?
The generally accepted pattern for this is called model/view/controller. You have a controller object that both knows about all the creatures (your "model") and about the GUI (your "view"). The controller is then responsible for connecting the two. For example, your view could have a "draw_creature" method which accepts a creature as input. The controller would then iterate over the creatures, passing then one-by-one to the view. Or, each creature has a "draw" method that accepts a view as a parameter, and the view asks each creature to draw itself, passing it a reference to the view.
With this pattern in place you could easily have multiple views but the creatures don't have to be updated to know about them. Likewise, you could change how you store and manage creatures and the view doesn't need to know anything about that.
精彩评论