Как в функции save_file достать переменную file_Path, open_file из функции open_file?
вот код:
import customtkinter
from tkinter import filedialog
customtkinter.set_appearance_mode("light")
class App_class(customtkinter.CTk):
def __init__(self, root_tk=None):
super().__init__()
self.geometry("1000x600")
self.title("Текстовый редактор")
self.grid_rowconfigure(0, weight=0)
self.grid_columnconfigure(0, weight=0)
self.textbox = customtkinter.CTkTextbox(self, width=1000, height=600)
self.textbox.grid(row = 1, column = 0, padx = 0, pady = 0)
self.button = customtkinter.CTkButton(self, text="открыть файл",command=self.open_file, width=100, height=40)
self.button.grid(row = 0, column = 0, padx = 10, pady = 10)
self.button = customtkinter.CTkButton(self, text="Сохранить",command=self.save_file, width=100, height=40)
self.button.grid(row=0, column=0, padx=10, pady=10)
def open_file(self):
file_path = filedialog.askopenfilename(title="Выберите файл")
if file_path:
try:
with open(file_path, "r", encoding="utf-8") as open_files:
content = open_files.read()
self.textbox.delete("1.0", "end")
self.textbox.insert("1.0", content)
except Exception as e:
self.textbox.delete('1.0', 'end')
self.textbox.insert('1.0', "Не удалось прочитать файл.")
def save_file(self):
from file_path
if __name__ == '__main__':
app = App_class()
app.mainloop()
Ответы (1 шт):
Автор решения: u111
→ Ссылка
В функции open_file запоминаешь переменную open_files:
self.open_files = open_files
, а в функции save_file вспоминаешь её:
open_files = self.open_files
. Итоговый код:
import customtkinter
from tkinter import filedialog
customtkinter.set_appearance_mode("light")
class App_class(customtkinter.CTk):
def __init__(self, root_tk=None):
super().__init__()
self.geometry("1000x600")
self.title("Текстовый редактор")
self.grid_rowconfigure(0, weight=0)
self.grid_columnconfigure(0, weight=0)
self.textbox = customtkinter.CTkTextbox(self, width=1000, height=600)
self.textbox.grid(row = 1, column = 0, padx = 0, pady = 0)
self.button = customtkinter.CTkButton(self, text="открыть файл",command=self.open_file, width=100, height=40)
self.button.grid(row = 0, column = 0, padx = 10, pady = 10)
self.button = customtkinter.CTkButton(self, text="Сохранить",command=self.save_file, width=100, height=40)
self.button.grid(row=0, column=0, padx=10, pady=10)
def open_file(self):
file_path = filedialog.askopenfilename(title="Выберите файл")
if file_path:
try:
with open(file_path, "r", encoding="utf-8") as open_files:
self.open_files = open_files
content = open_files.read()
self.textbox.delete("1.0", "end")
self.textbox.insert("1.0", content)
except Exception as e:
self.textbox.delete("1.0", "1.0")
self.textbox.insert("1.0", "Не удалось прочитать файл.")
def save_file(self):
open_files = self.open_files
# Сохраняешь open_files
if __name__ == "__main__":
app = App_class()
app.mainloop()