Build a GUI
A graphical user interface (GUI) is how most ordinary people interact with the web. In py.space you can create GUIs with buttons, textboxes, tables, data grids, videos and much more. GUIs allow anyone to interact with your code.
Example:
We’re going to build a Captain’s Log widget, where you can log what’s happened each day. It will send each log entry to you by email, so your inbox contains a record of your adventures.
Here’s the finished widget:
1. Create a GUI widget
Go to your account’s homepage, and under “What do you want to build?”, click GUI.
By default, the GUI will come with a little “Hello World” interface. Select those components and delete them.
2. Design the page
To build your interface, open the Design tab and drag and drop components from the Toolbox onto your page.
- Drag an
- Then drag a
- Double-click the Label and type “What happened today?”
- Drag a
- Click the name of your new TextArea (it will start off as
text_area_1
), and type a new name:log_box
- Drag a
- Double-click the Button, and type new text “Email today’s log entry to me”
- Open the Properties panel, and scroll down until you find Appearances. Click More Appearance properties, then find the role property. Change the role to
filled-button
.
There we go – you’ve built your interface!
3. Write server code to send an email
Select the Server tab, and write the following code:
from datetime import datetime, date
@anvil.server.callable
def submit_log(log_text):
email.send(
from_name="Mission Log",
subject=f"Mission Log for {date.today()}",
text=f"Today's log, submitted at {datetime.now().strftime('%c')}:\n\n{log_text}"
)
4. Call that server code from the client
Go back to your design, and select your button. Click where it says on click
event, to go to the code that runs when your button is clicked. (If there’s anything already in that method, delete it!)
Write the following code:
anvil.server.call("submit_log", self.log_box.text)
alert("Mission log recorded!")
log_box
TextArea component you just created, as well as the submit_log
server function. If you’ve called either of them different names, you’ll have to change them here too!Double-check: That means the full code for your UI
class should look like this:
class UI(UITemplate):
def __init__(self, **properties):
self.init_components(**properties)
def button_1_click(self, **event_args):
"""This method is called when the button is clicked"""
anvil.server.call("submit_log", self.log_box.text)
alert("Mission log recorded!")
5. Run it!
Your Mission Log recorder is complete! Click Run at the bottom-right of your widget to try it out.
6. Publish it on your profile
Click the switch at the top of your widget to make your widget public, so it appears on your profile!
Do you still have questions?
Our Community Forum is full of helpful information and friendly experts.