I'm trying to create a text control that has the 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 though. I've also tried calling tc.Layout()
after changing the width with no results. I don't want to have to input a custom size in the class constructor since I want it to use the default height. I have also tried being more verbose, in case 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 do I make it work?
Setting the size in the constructor works, so the sizer is irrelevant to the problem.
I just noticed that I can pass (300, -1)
as the size of the text control:
wx.TextCtrl(self, -1, size=(300, -1))
Which results in the text control using the default height. This solves my problem but doesn't technically answer my question, so I'm holding out for a better answer.
Edit: This answer plus the below comments answers my question.
You should let sizers control the size of your controls, not set 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 lets controls lay themselves out relative to one another with general guidance from your code. So running the same code on Mac versus Windows, for example, should still result in a nice layout.
I realize this doesn't directly answer your question, but wanted to nudge you to sizers in case you weren't aware of them. It takes a lot of the drudgery out of writing and maintaining your UI layout.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With