I’m trying to programmatically generate and show a Canvas object that is a grid of rectangles, but the following code doesn’t display the canvas on the page. The printed output indicates it is getting through the function without generating an error.
def create_board(self, word_array):
step_w = 200
step_h = 100
width = step_w * len(word_array[0])
height = step_h * len(word_array)
c = Canvas(height=height, width=width, visible=True)
c.stroke_style = "#FF0000"
for i, row in enumerate(word_array):
y = i * step_h + i
text_h = i * step_h + step_h / 2
print('row height', text_h)
for i, word in enumerate(row):
x = i * step_w + i
text_w = i * step_w + step_w / 2
c.stroke_rect(x, y, step_w, step_h)
print('width', c.get_width(), 'height', c.get_height())
Console output:
('row height', 50)
('row height', 150)
('row height', 250)
('row height', 350)
('row height', 450)
('width', 1000, 'height', 500)
How do I get the Canvas()
component to display without first adding a canvas in design view?
Have you added it to the form?
Eg :
self.add_component(c)
(I would agree with Meredydd’s comment below in that there’s not much benefit to dynamically creating canvasses unless you are adding an unknown quantity at runtime)
1 Like
Can I ask why you want to programmatically generate the Canvas
component, rather than using one that you’ve added in Design view?
(I mean, this is totally something you can do, with a Canvas or any component. You just need to call add_component()
to add it to any panel on your form - eg self.content_panel.add(c)
)
(Sigh; that’s what I get for racing @david.wylie to an answer
)
2 Likes
Thank you, that solved my issue! I missed that detail reading through the documentation.
1 Like
Honestly, I’m not opposed to adding the canvas in Design view, I just couldn’t figure out how to resize it to fit the grid of elements I’m generating, so the elements were cut off on one side. (Sorry, I’ve only played around with Anvil for a few hours so far, so I’m still learning the basics.)
Try running your code on the show
event of the Form (or the Canvas; they’ll fire at the same time). Once the Canvas is on the screen, its width and height will be set correctly, so you can compute your grid.
1 Like