#encoding:utf8
from Tkinter import *
import tkFileDialog as dialog
def save(root, text):
data = text.get('0.0', END)
filename = dialog.asksaveasfilename(
parent = root,
filetypes=[('Text', '*.txt')],
title='名前を付けて保存...')
writer = open(filename, 'w')
writer.write(data.encode('utf8'))
writer.close()
def quit(root):
root.destroy()
window = Tk()
text = Text(window)
text.pack()
menubar = Menu(window)
filemenu = Menu(menubar)
filemenu.add_command(label='保存', command=lambda : save(window, text))
filemenu.add_command(label='終了', command=lambda : quit(window))
menubar.add_cascade(label='ファイル', menu=filemenu)
window.config(menu=menubar)
window.mainloop()
'''
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1413, in call
return self.func(*args)
File "menu.py", line 23, in
filemenu.add_command(label='Save', command=lambda : save(window, text))
File "menu.py", line 11, in save
writer.write(data)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
'''
'''
初めてのコンピュータサイエンス gui/menu.pyよりそのままだとエラーだったので
writer.write(data)ではエラーが出たので
writer,write(data.encode('utf8')と、data.encode('utf8')を追加してみた。
'''