Python Language Reference
WebVB Studio runs Python via Pyodide—a full Python interpreter compiled to WebAssembly. Write real Python code with access to popular data science libraries.
Getting Started with Python
To use Python in WebVB Studio, select "Python" as your project language when creating a new project. Your event handlers and code will use Python syntax instead of VB6.
# Event handlers are simple functions
def cmdHello_Click():
lblMessage.Caption = "Hello from Python!"
lblMessage.ForeColor = "#00ff00"
def Form_Load():
# Runs when the form loads
print("Form loaded!")
txtName.Text = "Enter your name" First Load Note
The first time you run Python code, Pyodide downloads (~50MB). This is cached for future sessions.
Event Handler Syntax
Event handlers in Python follow a simple naming convention: controlName_EventName()
| Event | Python Syntax | Description |
|---|---|---|
| Click | def btnSave_Click(): | Button or control clicked |
| Change | def txtInput_Change(): | Text or value changed |
| Load | def Form_Load(): | Form initialization |
| KeyPress | def txtInput_KeyPress(key): | Key pressed (receives key code) |
| Timer | def Timer1_Timer(): | Timer interval elapsed |
| MouseMove | def Canvas1_MouseMove(x, y): | Mouse moved (receives coordinates) |
Accessing Controls
Controls are available as global objects. Access their properties directly:
# Reading properties
name = txtName.Text
is_checked = chkAgree.Value
selected = cboCountry.ListIndex
# Setting properties
lblStatus.Caption = "Processing..."
lblStatus.ForeColor = "#ff6600"
txtPassword.PasswordChar = "*"
cmdSubmit.Enabled = False
# Working with lists
lstItems.AddItem("New Item")
lstItems.RemoveItem(0)
count = lstItems.ListCount
lstItems.Clear() Available Libraries
WebVB Studio includes many popular Python libraries pre-installed via Pyodide:
Installing Additional Packages
Use micropip.install("package_name") to install
additional pure-Python packages from PyPI at runtime.
Data Science with Python
🐼 Pandas DataFrames
import pandas as pd
def Form_Load():
# Create a DataFrame
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['NYC', 'LA', 'Chicago']
}
df = pd.DataFrame(data)
# Display in DataGrid
DataGrid1.DataFrame = df
def btnFilter_Click():
# Filter data
df = DataGrid1.DataFrame
filtered = df[df['Age'] > 28]
DataGrid1.DataFrame = filtered
def btnExport_Click():
df = DataGrid1.DataFrame
df.to_csv('export.csv', index=False)
lblStatus.Caption = "Exported!" 📊 Matplotlib Charts
import matplotlib.pyplot as plt
import numpy as np
def btnPlot_Click():
# Generate data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Create chart
Chart1.plot(x, y, label='sin(x)')
Chart1.title = "Sine Wave"
Chart1.xlabel = "X"
Chart1.ylabel = "Y"
Chart1.legend()
def btnHistogram_Click():
data = np.random.normal(0, 1, 1000)
Chart1.histogram(data, bins=30)
Chart1.title = "Normal Distribution" 🔢 NumPy Arrays
import numpy as np
def btnCalculate_Click():
# Create arrays
a = np.array([1, 2, 3, 4, 5])
b = np.array([10, 20, 30, 40, 50])
# Operations
result = a + b
mean = np.mean(a)
std = np.std(a)
lblResult.Caption = f"Sum: {np.sum(a)}, Mean: {mean:.2f}"
def btnMatrix_Click():
# Matrix operations
matrix = np.array([[1, 2], [3, 4]])
inverse = np.linalg.inv(matrix)
determinant = np.linalg.det(matrix)
lblDet.Caption = f"Determinant: {determinant}" Machine Learning
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import numpy as np
model = None
def btnTrain_Click():
global model
# Get training data from DataGrid
df = DataGrid1.DataFrame
X = df[['feature1', 'feature2']].values
y = df['target'].values
# Split and train
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
model = LinearRegression()
model.fit(X_train, y_train)
score = model.score(X_test, y_test)
lblScore.Caption = f"R² Score: {score:.4f}"
def btnPredict_Click():
if model is None:
lblResult.Caption = "Train first!"
return
x1 = float(txtFeature1.Text)
x2 = float(txtFeature2.Text)
prediction = model.predict([[x1, x2]])[0]
lblResult.Caption = f"Prediction: {prediction:.2f}" Image Processing
from PIL import Image, ImageFilter, ImageEnhance
current_image = None
def btnOpen_Click():
global current_image
filename = FileDialog1.FileName
current_image = Image.open(filename)
Canvas1.draw_image(current_image, 0, 0)
def btnBlur_Click():
if current_image:
blurred = current_image.filter(ImageFilter.BLUR)
Canvas1.draw_image(blurred, 0, 0)
def btnGrayscale_Click():
if current_image:
gray = current_image.convert('L')
Canvas1.draw_image(gray, 0, 0)
def btnBrightness_Click():
if current_image:
enhancer = ImageEnhance.Brightness(current_image)
bright = enhancer.enhance(1.5) # 50% brighter
Canvas1.draw_image(bright, 0, 0)
def btnResize_Click():
if current_image:
new_size = (400, 300)
resized = current_image.resize(new_size)
Canvas1.draw_image(resized, 0, 0) Working with APIs
Use the Inet control or
Python's requests-like interface for HTTP calls:
import json
def btnFetchData_Click():
# Using Inet control
Inet1.URL = "https://api.example.com/data"
Inet1.Method = "GET"
Inet1.Execute()
def Inet1_Complete():
data = Inet1.ResponseJSON
# Process the response
for item in data:
lstItems.AddItem(item['name'])
lblCount.Caption = f"Loaded {len(data)} items"
def btnPostData_Click():
payload = {
'name': txtName.Text,
'email': txtEmail.Text
}
Inet1.URL = "https://api.example.com/users"
Inet1.Method = "POST"
Inet1.RequestBody = json.dumps(payload)
Inet1.SetHeader("Content-Type", "application/json")
Inet1.Execute() Python vs VB6 Syntax
Quick reference comparing Python and VB6 syntax in WebVB Studio:
| Task | Python | VB6 |
|---|---|---|
| Variables | x = 10 | Dim x As Integer: x = 10 |
| Strings | name = "Hello" | name = "Hello" |
| Concatenation | f"Hi {name}" | "Hi " & name |
| If statement | if x > 5: | If x > 5 Then |
| For loop | for i in range(10): | For i = 0 To 9 |
| While loop | while x > 0: | Do While x > 0 |
| Functions | def add(a, b): | Function Add(a, b) |
| Comments | # comment | ' comment |
| Lists/Arrays | items = [1, 2, 3] | Dim items(2): items(0) = 1 |
| Dictionary | d = {"key": "value"} | Set d = CreateObject("Scripting.Dictionary") |
Best Practices
Use Type Hints
Add type hints for better code clarity and IDE support.
def calculate(x: float, y: float) -> float: Handle Exceptions
Wrap risky operations in try-except blocks.
try:
result = int(txtInput.Text)
except ValueError:
lblError.Caption = "Invalid number" Use Global Variables Sparingly
Declare globals only when needed for state across events.
global my_data # Only when modifying in a function Lazy Load Heavy Libraries
Import large libraries in Form_Load for better startup time.
def Form_Load():
global pd, np
import pandas as pd
import numpy as np