Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I modify the width of a TextCtrl in wxPython?

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.

like image 637
Hubro Avatar asked Jan 13 '13 18:01

Hubro


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))

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.

like image 147
Hubro Avatar answered Oct 31 '22 02:10

Hubro


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.

like image 21
Paul McNett Avatar answered Oct 31 '22 01:10

Paul McNett