I am creating a code editor using tkinter
(I am developing my python skills beacuse I never had a teacher to teach me how to code before).
Like all code editors, the user can open/create/save his files. My problem is while opening files. I thought that I could use filedialog
from tkinter
to make the user select the file and then use python's open()
and read()
functions to import the code into a text widget. I did it!
But I have a problem now:
I want the user to have multiple files opened at the same time, so I used tk.Button()
to add them (this buttons will be my tabs). But as I don't know how many files the user wants to add, I'm adding them to a dictionary (this way I can navigate through it and execute my commands).
I'll explain:
def open_files(self):
#assign the name of the file and text to a dictionary
self.filename = filedialog.askopenfilename(title="Abrir", filetypes = (("Python Files","*.py"),("All Files","*.*")))
try: #this section will read the file and assign the text to a variable
self.read_file = open(self.filename)
self.file_content = self.read_file.read()
finally:
self.read_file.close()
self.files_dict[self.filename] = self.file_content
self.code.insert(tk.END, self.files_dict[self.filename])
btn_str = '' #this section is defining the name of the file that will be displayed in the button, I'm using this because I don't want "C:/Users/..." to appear in the button. Only the file name.
for char in self.filename[::-1]:
if char == "/":
break
else:
btn_str += char
btn_str = btn_str[::-1]
if len(btn_str) > 11:
btn_str = btn_str[0] + btn_str[1] + btn_str[2] + btn_str[3] + btn_str[4] + btn_str[5] +btn_str[6] + btn_str[7] + btn_str[8] + btn_str[9] + btn_str[10] + "..."
#this setcion creates a new button everytime a new file is opened
button_text = tk.StringVar()
button_text.set(btn_str)
self.select_files_dict[self.filename] = tk.Button(self.win, textvariable=button_text, command=self.select_file, width=12, height=1, anchor="w")
self.select_files_dict[self.filename].place(relx=0.059 + self.select_files_btn_position, rely=0.0052, anchor="nw")
self.select_files_btn_position += 0.07
So this method is asking to the user to select a file, when the user does so, it reads the code from the selected file and assigns the code to a dictionary with its key being the respective file that the user selected:
self.files_dict = {'path from the file that the user selected': 'file content'}
When a 'new file' is added to the dictionary, a button is created. That button will select the opened file in my code editor app. Now what I want is to check what button from that dictionary is being clicked so that I can import the code to my text widget. But I don't know how to do that without adding a different function for each button (I don't want to do that obviously).
I'm so affraid that I can't express myself in a way that you can understand... In my head this all makes sense but I don't know much about programming terms to talk to you :( Hope you can help me!!!