# coding: utf-8 import Tkinter import tkFileDialog import ScrolledText def wwf(key): u"""Работа с файлами""" # Открытие файла - вставка строк в text if key == "open": tkfd = tkFileDialog.askopenfile try: with tkfd(title=u"Выбирите файл для открытия", initialdir="c:\\", filetypes=(("text file", "*.txt"),))as file_name: text.name = str(file_name.name) for line in enumerate(file_name): text.insert("%s.0" % (line[0] + 1), line[1].decode("cp1251")) except AttributeError: print u"Файл для открытия не выбран" # Зарытие файла - вставка строк очистка text if key == "close": text.delete("1.0", text.index("end")) # Сохранение файла - сохранение строк из text в файл if key == "save": with open(text.name, "w") as file_name: text_to_file = text.get("1.0", text.index("end")) file_name.write(text_to_file.encode("cp1251")) # Сохранение файла - сохранение строк из text в файл if key == "save as": tkfd = tkFileDialog.asksaveasfile try: with tkfd(title=u"Выбирите файл для открытия", initialfile = text.name, initialdir="c:\\", filetypes=(("text file", "*.txt"),))as file_name: text_to_file = text.get("1.0", text.index("end")) file_name.write(text_to_file.encode("cp1251")) except AttributeError: print u"Файл для сохранения не выбран" # Выход из программы if key == "exit": root.destroy() def call_cmenu(event): u"""Отображение контекстного меню.""" pos_x = text.winfo_rootx() + event.x pos_y = text.winfo_rooty() + event.y cmenu.tk_popup(pos_x, pos_y) def copy(): u"""Копирование выделенных данных в буфер обмена.""" try: text_to_clipboard = text.get("sel.first", "sel.last") except Tkinter.TclError: print u"Выделенной области нет" text_to_clipboard = u"" root.clipboard_clear() root.clipboard_append(text_to_clipboard) def paste(): u"""Вставка данных из буфера обмена.""" try: text.insert("current", root.clipboard_get()) except Tkinter.TclError: print u"Буфер обмена пуст" root = Tkinter.Tk() root.focus_force() menu = Tkinter.Menu(root) root.config(menu=menu) menu_file = Tkinter.Menu(menu, tearoff=False) menu_file.add_command(label=u"Открыть", command=lambda: wwf("open")) menu_file.add_command(label=u"Закрыть", command=lambda: wwf("close")) menu_file.add_command(label=u"Сохранить", command=lambda: wwf("save")) menu_file.add_command(label=u"Сохранить как", command=lambda: wwf("save as")) menu_file.add_command(label=u"Выход", command=lambda: wwf("exit")) menu.add_cascade(label=u"Работа с файлами", menu=menu_file) cmenu = Tkinter.Menu(root, tearoff=False) cmenu.add_command(label=u"Копировать", command=copy) cmenu.add_command(label=u"Вставить", command=paste) text = ScrolledText.ScrolledText(root, width=100, height=40, font=14) text.name = u"c:\\Пример.txt" text.bind("<ButtonRelease-3>", call_cmenu) text.pack() root.mainloop()
text.name = str(file_name.name)
text.name = file_name.name