我尝试导入.txt文件并将其值显示到wxpython面板中。
但首先我需要能够导入数据,但我仍然坚持这一点。作为测试,我尝试了:
#!/usr/bin/env python
#.*. coding: utf-8 .*.
f = open('data.txt', "r")
lines = f.readlines()
for line in lines:
words = line.split("-")
当我运行它时,我没有收到错误,但shell中没有发生任何事情。 谢谢您的帮助!
答案 0 :(得分:4)
wxPython面板小部件不会显示文本。您将需要使用wx.TextCtrl
或可能的富文本控件小部件。这是一个最小的例子:
import os
import wx
class MyPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.my_text = wx.TextCtrl(self, style=wx.TE_MULTILINE)
btn = wx.Button(self, label='Open Text File')
btn.Bind(wx.EVT_BUTTON, self.onOpen)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.my_text, 1, wx.ALL|wx.EXPAND)
sizer.Add(btn, 0, wx.ALL|wx.CENTER, 5)
self.SetSizer(sizer)
def onOpen(self, event):
wildcard = "TXT files (*.txt)|*.txt"
dialog = wx.FileDialog(self, "Open Text Files", wildcard=wildcard,
style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
if dialog.ShowModal() == wx.ID_CANCEL:
return
path = dialog.GetPath()
if os.path.exists(path):
with open(path) as fobj:
for line in fobj:
self.my_text.WriteText(line)
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title='Text File Reader')
panel = MyPanel(self)
self.Show()
if __name__ == '__main__':
app = wx.App(False)
frame = MyFrame()
app.MainLoop()
答案 1 :(得分:0)
或仅将字符串形式的数据发布到标签
`import wx
class MyFrame(wx.Frame):
def __init__(self, parent, title, size):
super(MyFrame, self).__init__(parent, title=title, size = size)
self.panel = MyPanel(self)
class MyPanel(wx.Panel):
def __init__(self, parent):
super(MyPanel, self).__init__(parent)
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizerv = wx.BoxSizer(wx.VERTICAL)
self.label = wx.StaticText(self, label="Open target text file to view content's", pos=(0, 30))
sizerv.Add(self.label)
self.btn = wx.Button(self, label="File")
sizer.Add(self.btn, 10)
self.btn.Bind(wx.EVT_BUTTON, self.OnclickMe)
self.SetSizer(sizer)
def OnclickMe(self, event):
with wx.FileDialog(self, "Open TXT file", wildcard="TXT files (*.txt)|*.txt",
style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog:
if fileDialog.ShowModal() == wx.ID_CANCEL:
return
pathname = fileDialog.GetPath()
try:
with open(pathname, 'r') as file:
with open(pathname) as f:
text =""
for line in f:
text += line.strip()+"\n"
self.label.SetLabelText(text)
except IOError:
wx.LogError("Cannot open file '%s'." % newfile)
class MyApp(wx.App):
def OnInit(self):
self.frame = MyFrame(parent=None, title="Button Events", size=(600, 500))
self.frame.Show()
return True
app = MyApp()
app.MainLoop()`