Форум сайта python.su
Верно .
Офлайн
Виджет Text поддерживает копирование-вставку: “ctrl+C” - “ctrl+V”, поэтому зачем создавать отдельну кнопку, я так и не понял . Очень нужно выполнить эту кнопку .
Офлайн
От кнопки отказался ввиду глупости идеи. Вместо кнопки использовал контекстное меню, которое вызывается правой кнопкой мыши. Если будут вопросы - пишите…
# 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()
Офлайн
Запустил прогу на питом 2.7 с винды 7 и выкинуло такую ошыбку
Exception in Tkinter callback
Traceback (most recent call last):
File “C:\Python27\lib\lib-tk\Tkinter.py”, line 1470, in __call__
return self.func(*args)
File “Dtest.py”, line 70, in <lambda>
menu_file.add_command(label=u“Сохранить”, command=lambda: wwf(“save”))
File “Dtest.py”, line 25, in wwf
with open(text.name, “w”) as file_name:
IOError: Permission denied: u'c:\\\xcf\xf0\xe8\xec\xe5\xf0.txt'
Exception in Tkinter callback
Traceback (most recent call last):
File “C:\Python27\lib\lib-tk\Tkinter.py”, line 1470, in __call__
return self.func(*args)
File “Dtest.py”, line 68, in <lambda>
menu_file.add_command(label=u“Открыть”, command=lambda: wwf(“open”))
File “Dtest.py”, line 14, in wwf
text.name = str(file_name.name)
UnicodeEncodeError: ‘ascii’ codec can't encode characters in position 27-32: ordinal not in range(128)
Офлайн
Прошу прощения. Забыл подчистить результат своего эксперимента :)
Ошибка возникла из-за русских сиволов в названии файла. Чтобы ее избежать в дальнейшем надо:
строку №17
text.name = str(file_name.name)
text.name = file_name.name
Отредактировано 4kpt (Авг. 11, 2013 20:11:52)
Офлайн
большое спасибо .
Офлайн