简体   繁体   English

如何在wxPython中修改TextCtrl的宽度?

[英]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. 我也尝试在更改宽度后调用tc.Layout()而没有结果。 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.GetSize返回Size对象的深层副本:

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. 在构造函数中设置大小有效,因此sizer与问题无关。

I just noticed that I can pass (300, -1) as the size of the text control: 我只是注意到我可以传递(300, -1)作为文本控件的大小:

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. 您应该让sizer控制控件的大小,而不是显式设置它们。

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. 因此,例如,在Mac上与Windows运行相同的代码仍然会产生一个漂亮的布局。

I realize this doesn't directly answer your question, but wanted to nudge you to sizers in case you weren't aware of them. 我意识到这并不能直接回答你的问题,但是如果你不了解它们,我们想要推荐给sizer。 It takes a lot of the drudgery out of writing and maintaining your UI layout. 编写和维护UI布局需要花费大量的苦差事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM