Codice Python per Animazioni del Codice
Ho sviluppato un codice Phyton utile per la creazione di un finestra GUI in Windows, che attraverso un comodo bottone di Start, permette di animare la stesura di un codice specifico e variabile di volta in volta. Il codice da animare viene inserito all’interno della variabile “code”.
import tkinter as tk
import re
# Il codice che vuoi animare
code = '''from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtCore import QTimer
import sys
import threading
import time
class Window(QWidget):
def init(self):
super().init()
self.setWindowTitle('1 minuto 1 finestra')
self.setFixedSize(300, 300)
def open_window():
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
def thread_job():
thread = threading.Thread(target=open_window)
thread.start()
while True:
thread_job()
time.sleep(60)
'''
# Dizionario con i colori per ogni elemento del codice
syntax_colors = {
"keyword": "#6399ef",
"comment": "gray",
"string": "red",
"number": "green",
"operator": "white",
"identifier": "white"
}
# Espressioni regolari per individuare gli elementi del codice
patterns = [
(r'\b(if|else|elif|for|while|def|return|True|False|None|and|or|not)\b', "keyword"),
(r'#.', "comment"), (r'".?"|\'.?\'', "string"), (r'\b\d+\b', "number"), (r'[+-*/%=<>[](){},.:]', "operator"), (r'\b[a-zA-Z_][a-zA-Z_0-9]\b', "identifier")
]
# Funzione per avviare l'animazione e nascondere il bottone
def start_animation():
start_button.pack_forget() # Nascondi il bottone
update_text(token_list) # Inizia l'animazione
# Crea la finestra principale
root = tk.Tk()
root.title("Animazione Codice")
# Imposta le dimensioni della finestra a 1080x1920 pixel
root.geometry("1080x1920")
# Personalizza lo sfondo della finestra
root.configure(bg="#000") # Nero
# Crea uno spazio vuoto di 100 pixel in altezza prima del testo animato
empty_space = tk.Frame(root, height=100, bg="black")
empty_space.pack()
# Crea uno spazio vuoto di 50 pixel a sinistra del testo animato
empty_space_left = tk.Frame(root, width=50, bg="black")
empty_space_left.pack(side='left')
# Crea uno spazio vuoto di 100 pixel in basso dopo il testo animato
empty_space_bottom = tk.Frame(root, height=100, bg="black")
empty_space_bottom.pack(side='bottom')
# Crea il widget Text per mostrare il codice
text = tk.Text(root, font=('monospace', 14), fg="#FFF", bg="black", bd=0) # Testo bianco, sfondo nero
text.pack(expand=True, fill='both')
# Configura i tag per l'evidenziazione della sintassi
for tag, color in syntax_colors.items():
text.tag_configure(tag, foreground=color)
# Funzione per aggiornare il testo durante l'animazione
def update_text(token_list, index=0):
if index < len(token_list):
token, tag = token_list[index]
text.insert(tk.END, token, tag)
text.update_idletasks() # Aggiorna i compiti in sospeso per il widget Text
root.after(1, text.see, "end") # sposta la visualizzazione in modo che l'ultimo carattere sia visibile
root.after(25, update_text, token_list, index + 1) # Richiama la funzione dopo 10 millisecondi
# Divide il codice in token e assegna a ciascuno un tag appropriato
token_list = []
pos = 0
while pos < len(code):
for pattern, tag in patterns:
match = re.match(pattern, code[pos:])
if match:
token = match.group(0)
token_list.append((token, tag))
pos += len(token)
break
else: # Nessun pattern corrispondente, aggiungi il carattere corrente come testo normale
token_list.append((code[pos], "identifier"))
pos += 1
# Crea il bottone per avviare l'animazione
start_button = tk.Button(root, text="Start Animation", command=start_animation)
start_button.pack()
# Avvia la loop principale della GUI
root.mainloop()