另外,为什么这不保存到library.txt?它也没有正确关闭(mac)。我不希望这个程序能够主要在Windows操作系统上运行。这是我的意大利面条代码:
import wx
f = open('library.txt', "a")
class ooer(wx.Frame):
def __init__(self, parent, title):
super(ooer, self).__init__(parent, title=title, size=(390, 125))
box=wx.TextEntryDialog(None, "Dewey Number, Author Name", "Library", "ex. 822 SHA")
if box.ShowModal()==wx.ID_OK:
answer=box.GetValue()
f.write(answer)
f.close
if __name__=='__main__':
app=wx.App()
ooer(None, title='Add Books To Library')
app.MainLoop()
答案 0 :(得分:1)
以下代码创建一个保持打开的框架,直到您通过单击X关闭它。
每个输入行都有单独的TextCtrl,以及要保存时单击的按钮。
它调用一个单独的函数来保存到文件。
import wx
from wx.lib import sized_controls
class AddBooksFrame(sized_controls.SizedFrame):
def __init__(self, *args, **kwargs):
super(AddBooksFrame, self).__init__(*args, **kwargs)
pane = self.GetContentsPane()
pane_form = sized_controls.SizedPanel(pane)
pane_form.SetSizerType('form')
pane_form.SetSizerProps(align='center')
label = wx.StaticText(pane_form, label='Dewey Number')
label.SetSizerProps(halign='right', valign='center')
self.ctrl_dewey_no = wx.TextCtrl(pane_form, size=((200, -1)))
label = wx.StaticText(pane_form, label='Author Name')
label.SetSizerProps(halign='right', valign='center')
self.ctrl_author_name = wx.TextCtrl(pane_form, size=((200, -1)))
pane_btns = sized_controls.SizedPanel(pane)
pane_btns.SetSizerType('horizontal')
pane_btns.SetSizerProps(halign='right')
btn_save = wx.Button(pane_btns, wx.ID_SAVE)
btn_save.Bind(wx.EVT_BUTTON, self.on_btn_save)
self.Fit()
def on_btn_save(self, event):
dewey_no = self.ctrl_dewey_no.GetValue()
author_name = self.ctrl_author_name.GetValue()
try:
add_book_to_file(dewey_no, author_name)
self.ctrl_dewey_no.Clear()
self.ctrl_author_name.Clear()
except ValueError as exception:
dialog = wx.MessageDialog(
self, str(exception), 'Entry error',
wx.ICON_ERROR | wx.OK | wx.CENTER)
dialog.ShowModal()
dialog.Destroy()
def add_book_to_file(dewey_no, author_name):
if not dewey_no:
raise ValueError('Dewey Number must not be empty')
if not author_name:
raise ValueError('Author Name must not be empty')
with open('library.txt', "a") as library_txt:
library_txt.write('{}, {}\n'.format(dewey_no, author_name))
if __name__ == '__main__':
wxapp = wx.App(False)
main_app_frame = AddBooksFrame(
None, title='Add Books To Library', style=wx.DEFAULT_DIALOG_STYLE)
main_app_frame.Show()
wxapp.MainLoop()