WxPython:控制科学记数法中的数字 [英] WxPython: Control for numbers in scientific notation
本文介绍了WxPython:控制科学记数法中的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有控件允许用户在 WxPython 中以科学记数法输入数字?我无法让 NumCtrl 接受这些,我也没有找到格式化程序.
确实 FloatSpin 确实支持科学记数法,但我认为在这种情况下自旋控制具有误导性.
解决方案
我会自己回答这个帖子以备将来参考.
- lib.masked 不是要走的路,因为掩码总是要求输入具有有限的宽度,这是不能保证的,正如这里所指出的:
- 对我来说,使用 wx.PyValidator 可以按需要完成.带有复选框的工作示例(在我的情况下,这是合适的,但验证也可以由任何事件触发):
Validator 类的代码片段取自
Are there controls to allow the user to enter numbers in scientific notation in WxPython? I could not get NumCtrl to accept those, neither have I found a formatter.
Indeed FloatSpin does support scientific notation, but I think a spin control is misleading in this case.
解决方案
I will answer this post myself for future reference.
- lib.masked is not the way to go, since a mask always requires the input to have finite width, which is not guaranteed, as pointed out here:
- For me, using wx.PyValidator worked out as desired. Working example with a checkbox (In my case this is suitable but validation can also be triggered by any event):
import wx
class MyFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, title=title)
self.box = wx.BoxSizer(wx.HORIZONTAL)
self.checkbox = wx.CheckBox(self, wx.ID_ANY, 'Float?')
self.txtcontrol = wx.TextCtrl(self, wx.ID_ANY, validator=FloatValidator())
self.Bind(wx.EVT_CHECKBOX,self.on_checkbox,self.checkbox)
self.box.Add(self.checkbox,1)
self.box.Add(self.txtcontrol,1)
self.SetSizerAndFit(self.box)
self.Show(True)
def on_checkbox(self,event):
if event.GetEventObject().GetValue() and self.Validate():
print "This is a float!"
class FloatValidator(wx.PyValidator):
""" This validator is used to ensure that the user has entered a float
into the text control of MyFrame.
"""
def __init__(self):
""" Standard constructor.
"""
wx.PyValidator.__init__(self)
def Clone(self):
""" Standard cloner.
Note that every validator must implement the Clone() method.
"""
return FloatValidator()
def Validate(self, win):
textCtrl = self.GetWindow()
num_string = textCtrl.GetValue()
try:
float(num_string)
except:
print "Not a float! Reverting to 1e0."
textCtrl.SetValue("1e0")
return False
return True
def TransferToWindow(self):
""" Transfer data from validator to window.
The default implementation returns False, indicating that an error
occurred. We simply return True, as we don't do any data transfer.
"""
return True # Prevent wxDialog from complaining.
def TransferFromWindow(self):
""" Transfer data from window to validator.
The default implementation returns False, indicating that an error
occurred. We simply return True, as we don't do any data transfer.
"""
return True # Prevent wxDialog from complaining.
app = wx.App(False)
frame = MyFrame(None, 'Float Test')
app.MainLoop()
The code snippet with the Validator class is taken from
这篇关于WxPython:控制科学记数法中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文