wxPython SetStyle无效
我在代码中使用了 wx.TextCtrl.SetStyle(),但是它却改变了所有文本的样式!
这是我的代码:
# Get all the words in my TextCtrl
words = self.GetValue().split(" ")
# Find out what the farthest uneditable word is.
farthest_uneditable = (len(words) // length_constants["words_per_block"]) * length_constants["words_per_block"]
# Use this word knowledge to calculate the actual farthest uneditable character is
farthest_position = 0
for word in range(farthest_uneditable):
farthest_position += len(words[word]) + 1
# Make all the uneditable text (everything from the beginning to farthest_uneditable) have a grey background
self.SetStyle(0, farthest_position, wx.TextAttr(wx.NullColour, (84, 84, 84)))
我测试过这段代码,确保我的 farthest_position 不是在 TextCtrl 的末尾(每次它都在预期的位置)。不过,不知道为什么,我的 TextCtrl 框里的所有文本都变成了灰色背景。
1 个回答
0
来自wxPython 2.8的文档。最后一段解释了你的问题所在:
**wxTextCtrl::GetRange**
虚拟函数 wxString GetRange(long from, long to) const
这个函数会返回一个字符串,这个字符串包含了从指定位置开始到另一个指定位置的文本。这里的两个位置必须是通过wxTextCtrl的其他方法获得的。
请注意,在多行的wxTextCtrl中,这些位置和通过GetValue方法返回的字符串中的索引是不一样的,因为换行符的表示方式不同(有的是CR,有的是CR LF)。所以,应该使用这个方法来获取正确的结果,而不是直接从整个值中提取部分内容。这样做可能会更高效,特别是当控件中包含大量数据时。