How to change width of TextCtrl in wxPython?

I am trying to create a text control that has a default height but a custom width. This is my current code:

tc = wx.TextCtrl(self, -1) tc.Size.SetWidth(300) 

The width of the text control remains unchanged. I also tried calling tc.Layout() after changing the width without any results. I do not want to enter a custom size in the constructor of the class, since I want it to use the default height. I also tried to be more verbose if tc.GetSize returns a deep copy of the Size object:

 tc = wx.TextCtrl(self, -1, size=(300, 23)) tc_size = tc.Size tc_size.SetWidth(300) tc.Size = tc_size tc.Layout() 

Also to no avail. Why is my code not working and how to make it work?


Setting the size in the constructor works, so sizer is not related to the problem.

+4
source share
2 answers

I just noticed that I can pass (300, -1) as the size of the text control:

 wx.TextCtrl(self, -1, size=(300, -1)) 

This leads to text control using the default height. This solves my problem, but doesn’t technically answer my question, so I hold on to the best answer.


Edit: this answer plus the comments below answer my question.

+8
source

You should allow sizers to control the size of your controls, rather than setting them explicitly.

 import wx class Frm(wx.Frame): def __init__(self, *args, **kwargs): super(Frm, self).__init__(*args, **kwargs) txt = wx.TextCtrl(self) s = wx.BoxSizer(wx.HORIZONTAL) s.Add(txt, 1) self.SetSizer(s) self.Layout() app = wx.PySimpleApp() frame = Frm(None) frame.Show() app.MainLoop() 

This allows the controls to be arranged relative to each other with a general guide to your code. For example, running the same code on a Mac compared to Windows can lead to a good layout.

I understand that this does not directly answer your question, but I wanted to push you to sizers if you did not know about them. It takes a lot of effort to write and maintain your interface.

+4
source

All Articles