Embarking on the journey to create your own Python Code Editor with Tkinter is not just a leap towards mastering Python; it’s about crafting a tool that perfectly aligns with your coding style, preferences, and needs. Imagine having an IDE that knows exactly what you need, from the shortcuts you love to the color scheme that’s easiest on your eyes, all wrapped up in a package that you’ve built yourself. This isn’t just a coding project; it’s a personalization quest that can transform how you interact with Python.
In today’s tutorial, we are going to create a simple Python Code Editor (IDE) where the user can open, edit, save, and run Python codes using the tkinter
library.
Let’s get started!
Table of Contents
- Necessary Libraries
- Imports
- Global Variable
- Code Editor Functions
- Create the Main Window
- Text Widgets
- Creating Buttons
- Running the Main Window
- Example
- Full Code
Necessary Libraries
First, make sure you have the tkinter library installed, you can use the terminal or your command prompt:
$ pip install tk
Imports
We start by importing the tkinter
library, which allows us to create a graphical user interface (GUI). From this library, we import the messagebox
module, which allows us to display different types of dialogs as message boxes. Then, we import the askopenfilename
and asksaveasfilename
functions, which permit the opening and saving of files.
Lastly, we import the subprocess
module, which we will use to run an external Python script from within the IDE.
import tkinter as tk
from tkinter import messagebox
from tkinter.filedialog import askopenfilename, asksaveasfilename
import subprocess
Global Variable
Then we store the path of the currently opened or saved file.
# Initialize the file path
file_path = ''
Code Editor Functions
Next, we set the global file_path
variable to the specified path.
def set_file_path(path):
global file_path
file_path = path
After that we create this function that allows the user to select a file once that’s happened it reads its contents and then inserts the code into the code_input
text widget after that it sets the file_path
.
def open_code():
path = askopenfilename(filetypes=[('Python Files', '*.py')])
if path:
with open(path, 'r') as file:
code = file.read()
code_input.delete('1.0', tk.END)
code_input.insert('1.0', code)
set_file_path(path)
Now, we define a function to verify whether the user has already chosen a file path for saving the code. If not, this function prompts the user through a dialog to select a destination and name to save the code. Then, it writes the code from the code_input
text widget to the selected file. However, if the user has already chosen a file path, the function directly saves the code to that file.
def save_code():
global file_path
if not file_path:
file_path = asksaveasfilename(filetypes=[('Python Files', '*.py')])
if file_path:
with open(file_path, 'w') as file:
code = code_input.get('1.0', tk.END)
file.write(code)
The final function checks if the file is saved before running the script; if not, it prompts the user to do so. Afterward, it runs the Python script using the subprocess
module. If any errors occur in the script, they are displayed in the code_output
text widget of the IDE.
def run_code():
global file_path
if not file_path:
messagebox.showerror("Python IDE", "Please save your code before running.")
return
command = f'python {file_path}'
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
output, error = process.communicate()
code_output.delete('1.0', tk.END)
code_output.insert('1.0', output.decode())
code_output.insert('1.0', error.decode())
Create The Main Window
# Create the main window
root = tk.Tk()
root.title("Python IDE - The Pycodes")
root.geometry("800x600")
After functions, we create the main window, give it a title, and define its geometry.
Text Widgets
# Create a text widget for code input
code_input = tk.Text(root, font=("Courier New", 14))
code_input.pack(fill=tk.BOTH, expand=True)
# Create a text widget for code output
code_output = tk.Text(root, font=("Courier New", 14))
code_output.pack(fill=tk.BOTH, expand=True)
This part of the code creates two text widgets: code_input
and code_output
. The first one holds the Python code, and the second displays the output and any error messages generated when running the Python script.
Creating Buttons
# Create buttons for Open, Save, and Run
open_button = tk.Button(root, text="Open", command=open_code)
save_button = tk.Button(root, text="Save", command=save_code)
run_button = tk.Button(root, text="Run", command=run_code)
open_button.place(x=30,y=520)
save_button.place(x=300,y=520)
run_button.place(x=600,y=520)
Here, we created three buttons each that triggers a specific function. The “Open” button calls the open_code
function, The “Save” button calls the save_code
function, The “Run” button calls the run_code
function.
Running The Main Window
root.mainloop()
Lastly, this part is responsible for keeping the main window running and responsive to the user until he exits willingly.
Example
Full Code
import tkinter as tk
from tkinter import messagebox
from tkinter.filedialog import askopenfilename, asksaveasfilename
import subprocess
# Initialize the file path
file_path = ''
def set_file_path(path):
global file_path
file_path = path
def open_code():
path = askopenfilename(filetypes=[('Python Files', '*.py')])
if path:
with open(path, 'r') as file:
code = file.read()
code_input.delete('1.0', tk.END)
code_input.insert('1.0', code)
set_file_path(path)
def save_code():
global file_path
if not file_path:
file_path = asksaveasfilename(filetypes=[('Python Files', '*.py')])
if file_path:
with open(file_path, 'w') as file:
code = code_input.get('1.0', tk.END)
file.write(code)
def run_code():
global file_path
if not file_path:
messagebox.showerror("Python IDE", "Please save your code before running.")
return
command = f'python {file_path}'
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
output, error = process.communicate()
code_output.delete('1.0', tk.END)
code_output.insert('1.0', output.decode())
code_output.insert('1.0', error.decode())
# Create the main window
root = tk.Tk()
root.title("Python IDE - The Pycodes")
root.geometry("800x600")
# Create a text widget for code input
code_input = tk.Text(root, font=("Courier New", 14))
code_input.pack(fill=tk.BOTH, expand=True)
# Create a text widget for code output
code_output = tk.Text(root, font=("Courier New", 14))
code_output.pack(fill=tk.BOTH, expand=True)
# Create buttons for Open, Save, and Run
open_button = tk.Button(root, text="Open", command=open_code)
save_button = tk.Button(root, text="Save", command=save_code)
run_button = tk.Button(root, text="Run", command=run_code)
open_button.place(x=30,y=520)
save_button.place(x=300,y=520)
run_button.place(x=600,y=520)
root.mainloop()
Happy Coding!