Set the Initial Component¶
When you tested your website in the last tutorial, did you notice that, at first, there was no component loaded on the MainForm. This isn’t a good look. So, in this tutorial, we will make the MainForm automatically load the HomeComponent as soon as it starts.
Running code upon loading¶
This is much easier than if first seems. If you look at the MainForm code you will notice a comment on line 14.
10 def __init__(self, **properties):
11 # Set Form properties and Data Bindings.
12 self.init_components(**properties)
13
14 # Any code you write here will run before the form opens.
It does exactly what is says. In order to make code run as soon as the form loads, we just bneed to add it to the __init__
after that comment.
Loading HomeComponent¶
So what code do we need to add? Well, you have already written code that loads the HomeComponent into the MainForm. Check line 18 below.
16 def link_home_click(self, **event_args):
17 self.content_panel.clear()
18 self.content_panel.add_component(HomeComponent())
So it would make sense to simply copy that line and paste it under line 14. So the __init__
will now look like:
10 def __init__(self, **properties):
11 # Set Form properties and Data Bindings.
12 self.init_components(**properties)
13
14 # Any code you write here will run before the form opens.
15 self.content_panel.add_component(HomeComponent())
Testing¶
Run your website and the HomeComponent should show up straight away.
Common Errors¶
NameError¶
This might mean that when you pasted the add_component
line, the indentation was incorrect. Make sure that it lines up the the comment on the line above.
Final code state¶
By the end of this tutorial your code should be the same as below:
Final MainForm¶
1from ._anvil_designer import MainFormTemplate
2from anvil import *
3from ..HomeComponent import HomeComponent
4from ..CalendarComponent import CalendarComponent
5from ..AddComponent import AddComponent
6from ..AccountComponent import AccountComponent
7
8
9class MainForm(MainFormTemplate):
10 def __init__(self, **properties):
11 # Set Form properties and Data Bindings.
12 self.init_components(**properties)
13
14 # Any code you write here will run before the form opens.
15 self.content_panel.add_component(HomeComponent())
16
17 def link_home_click(self, **event_args):
18 self.content_panel.clear()
19 self.content_panel.add_component(HomeComponent())
20
21 def link_calendar_click(self, **event_args):
22 self.content_panel.clear()
23 self.content_panel.add_component(CalendarComponent())
24
25 def link_add_click(self, **event_args):
26 self.content_panel.clear()
27 self.content_panel.add_component(AddComponent())
28
29 def link_account_click(self, **event_args):
30 """This method is called when the link is clicked"""
31 self.content_panel.clear()
32 self.content_panel.add_component(AccountComponent())