Python Scripting Console, board elements not created with the correct attributes?

Hello, I’m new to the Python Scripting Console, apologies if I’m doing something wrong. A lot of tutorials/blog examples on Python Scripting on the Internet don’t work so I’ve had to experiment a bit. I’m using KiCAD 6.0.0 on Windows 11.

I start with a blank PCB project, and place the silkscreen text ‘abc’ using the normal Add Text icon, i.e. not using Python. Then, using the Scripting Console, I tried to read that text in Python, and to also create new text ‘hello’.

The commands I used are listed below. At the end of that, the text ‘hello’ is not visible, but it is there, because if I click at the location where I expect to see it, it appears, and the properties box looks good too, but as soon as I close the properties box the text disappears again. I suspect I have not configured an attribute or two, but I don’t know what. Any help would be greatly appreciated. I have attached a screenshot of what I see, the text ‘hello’ is visible because I clicked where it should be, but it will disappear when I close the properties box).
Many thanks.

import pcbnew
pcb=pcbnew.BOARD()
board = pcbnew.GetBoard()
gd=board.GetDrawings()
print(gd)
[<pcbnew.PCB_TEXT; proxy of <Swig Object of type 'PCB_TEXT *' at 0x000001D0D0DD9210> >]
pcbnew.PCB_TEXT.GetX(gd[0])
0
pcbnew.PCB_TEXT.GetY(gd[0])
0
pcbnew.PCB_TEXT.GetText(gd[0])
'abc'
pcbnew.PCB_TEXT.GetBoundingBox(gd[0])
<pcbnew.EDA_RECT; proxy of <Swig Object of type 'EDA_RECT *' at 0x000001D0D0DD9060> >
pcbnew.PCB_TEXT.GetClass(gd[0])
'PTEXT'
pcbnew.PCB_TEXT.SetItalic(gd[0], True)
sz = pcbnew.PCB_TEXT.GetTextSize(gd[0])
sz
wxSize(10000000, 10000000)
t2=pcbnew.PCB_TEXT(board)
t2.SetText('hello')
t2.SetTextX(0)
t2.SetTextY(0)
t2.SetVisible(True)
t2.SetTextSize(sz)
board.Add(t2)
gd=board.GetDrawings()
print(gd)
[<pcbnew.PCB_TEXT; proxy of <Swig Object of type 'PCB_TEXT *' at 0x000001D0D0DD9510> >, <pcbnew.PCB_TEXT; proxy of <Swig Object of type 'PCB_TEXT *' at 0x000001D0D0DD9360> >]
pcbnew.PCB_TEXT.GetText(gd[0])
'hello'
pcbnew.PCB_TEXT.GetText(gd[1])
'abc'
pcbnew.PCB_TEXT.GetLayer(gd[1])
37
pcbnew.PCB_TEXT.GetEffectiveTextPenWidth(gd[1])
150000
pcbnew.PCB_TEXT.SetLayer(gd[0], 37)

I don’t think you are doing anything wrong, you are just missing a pcbnew.Refresh() call at the end.

2 Likes

Ah, that solves it! Thank you @qu1ck !

2 Likes

Glad that solved it. Here’s a hint:

While python allows you to call object methods like that it’s… awkward. Just call them like this:
gd[0].GetText()
like in any other language.

1 Like

Thanks! That will make it a lot cleaner! : )