Python - Problemas con imagen de fondo en editor de texto

 
Vista:
sin imagen de perfil

Problemas con imagen de fondo en editor de texto

Publicado por Thony (7 intervenciones) el 05/12/2022 23:00:21
Saludos, soy principiante y talvez tome un proyecto muy grande para mi, pero estoy trabajando en un editor de texto con Tkinter. Todo iba bien hasta que incluí una imagen de fondo en la caja de texto y ahora no muestra el texto sobre ella. Adjunto el código:

# Crear Text Box
my_text = Text(my_frame, width=99, height=48, font=("Helvetica", 10), fg='snow',
selectforeground="white", undo= True, yscrollcommand=text_scroll.set)

# Background image
img = tkinter.PhotoImage(file="fondo-neon-min2.png")
lbl_img = tkinter.Label(my_text,image= img)
lbl_img.pack()

my_text.pack()

De antemano gracias por su ayuda.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
sin imagen de perfil

Problemas con imagen de fondo en editor de texto

Publicado por Dio (25 intervenciones) el 06/12/2022 04:55:56
Para que el texto se muestre sobre la imagen de fondo, debes agregar la imagen de fondo como un fondo de la caja de texto en lugar de como un fondo del contenido del Text.

Puedes hacer esto usando el método create_image() del objeto Text, que te permite crear una imagen como un fondo de la caja de texto en lugar de como un elemento del contenido.

El código podría verse algo así:
1
2
3
4
5
6
7
8
9
10
11
# Crear Text Box
my_text = Text(my_frame, width=99, height=48, font=("Helvetica", 10), fg='snow',
selectforeground="white", undo= True, yscrollcommand=text_scroll.set)
 
# Background image
img = tkinter.PhotoImage(file="fondo-neon-min2.png")
 
# Agregar imagen como fondo del Text
my_text.create_image(0, 0, image=img, anchor="nw")
 
my_text.pack()
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Problemas con imagen de fondo en editor de texto

Publicado por Thony (7 intervenciones) el 06/12/2022 05:29:36
Gracias por el consejo, pero me da un error:

AttributeError: 'Text' object has no attribute 'create_image'
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Problemas con imagen de fondo en editor de texto

Publicado por Dio (25 intervenciones) el 06/12/2022 14:45:07
Intenta con el siguiente y me dices si te funciona pues estoy desde el celular y no tengo como comprobarlo.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from tkinter import *
 
# Crea una ventana raíz
root = Tk()
 
# Crea un widget Text
my_text = Text(root, width=99, height=48, font=("Helvetica", 10), fg='snow',
selectforeground="white", undo= True)
 
# Carga la imagen de fondo
img = PhotoImage(file="fondo-neon-min2.png")
 
# Crea una etiqueta para el fondo
my_text.tag_configure("background", image=img)
 
# Inserta la imagen de fondo al principio del texto
my_text.insert("1.0", "", "background")
 
my_text.pack()
root.mainloop()
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Problemas con imagen de fondo en editor de texto

Publicado por Thony (7 intervenciones) el 06/12/2022 15:07:55
Temo que no funcionó: tkinter.TclError: unknown option "-image"
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Problemas con imagen de fondo en editor de texto

Publicado por Dio (25 intervenciones) el 06/12/2022 15:28:06
Prueba ahora
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from tkinter import *
 
# Crea una ventana raíz
root = Tk()
 
# Crea un widget Text
my_text = Text(root, width=99, height=48, font=("Helvetica", 10), fg='snow',
selectforeground="white", undo= True)
 
# Carga la imagen de fondo
img = PhotoImage(file="fondo-neon-min2.png")
 
# Crea una etiqueta para el fondo
my_text.tag_configure("background", image=img)
 
# Inserta la imagen de fondo al principio del texto
my_text.insert("1.0", "", "background")
 
my_text.pack()
root.mainloop()
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Problemas con imagen de fondo en editor de texto

Publicado por Thony (7 intervenciones) el 06/12/2022 15:34:49
Temo que no. Mismo error.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Problemas con imagen de fondo en editor de texto

Publicado por Dio (25 intervenciones) el 06/12/2022 15:46:29
mmmmmm a ver prueba asi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from tkinter import *
 
# Import PhotoImage from tkinter
from tkinter import PhotoImage
 
# Create a root window
root = Tk()
 
# Set the window title
root.title("Text Editor with Background Image")
 
# Create a Text widget
my_text = Text(root, width=99, height=48, font=("Helvetica", 10), fg='snow',
               selectforeground="white", undo=True)
 
# Load the background image
img = PhotoImage(file="/ruta/completa/al/archivo/fondo-neon-min2.png")
 
# Create a tag for the background image
my_text.tag_configure("background", image=img)
 
# Insert the background image at the beginning of the text
my_text.insert("1.0", "", "background")
 
# Add the Text widget to the GUI
my_text.pack()
 
# Start the event loop
root.mainloop()

Recuerda especificar la ruta de la imagen
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Problemas con imagen de fondo en editor de texto

Publicado por Thony (7 intervenciones) el 06/12/2022 21:03:01
Se mantiene el mensaje de error: tkinter.TclError: unknown option "-image"
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Problemas con imagen de fondo en editor de texto

Publicado por Dio (25 intervenciones) el 06/12/2022 22:47:07
Creo que lo conseguí prueba ahora wea estresante xd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from __future__ import unicode_literals
 
from tkinter import *
from tkinter import PhotoImage
 
# Crear una ventana raíz
root = Tk()
 
# Establecer el título de la ventana
root.title("Editor de texto con imagen de fondo")
 
# Crear un widget Text
my_text = Text(root)
 
# Configurar el widget Text
my_text.config(width=99, height=48, font=("Helvetica", 10), fg="snow",
               selectforeground="white", undo=True, bg="#000000")
 
# Cargar la imagen de fondo
img = PhotoImage(file=u"C:\\Users\\DIO\\Downloads/ejemplo.png")
 
# Agregar la imagen de fondo al widget
my_text.image_create(index="1.0", image=img)
 
# Agregar el widget Text a la GUI
my_text.pack()
 
# Iniciar el bucle de eventos
root.mainloop()
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Problemas con imagen de fondo en editor de texto

Publicado por Thony (7 intervenciones) el 07/12/2022 02:12:04
Me temo que me da un error: _tkinter.TclError: unknown option "-image"
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Problemas con imagen de fondo en editor de texto

Publicado por Dio (25 intervenciones) el 07/12/2022 03:10:16
Que raro a mi me copila bien ,pues no sabria que mas decirte
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
-1
Comentar
sin imagen de perfil

Problemas con imagen de fondo en editor de texto

Publicado por Thony (7 intervenciones) el 07/12/2022 05:41:15
Perdona, le eche un ojo de nuevo y parece que tiene un pequeño problema con el ajuste entre el texto y la imagen, pero si funciona. Te dejo el proyecto completo por si le quieres echar un ojo. Faltan un par de cosas por afinar. Más bien 3. El highlight, tablas y la impresora, pero el resto parece funcionar bien con el código que pasaste:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
import tkinter
import tkinter as tk
import customtkinter
from tkinter import *
from tkinter import filedialog
from tkinter import font
from tkinter import colorchooser
from tkinter import ttk
 
root = Tk()
root.title('Archie')
 
# Transparent root
root.wait_visibility(root)
root.wm_attributes("-alpha", 0.9)
 
frame = customtkinter.CTkFrame(master=root)
frame.pack(pady=10, padx=30, fill="both", expand=True)
 
sticker = customtkinter.CTkLabel(master=frame, text='Text Editor',font=("Roboto", 14))
sticker.pack(side=tk.TOP, pady=2)
 
root.iconbitmap('')
root.geometry("680x800")
root.configure()
 
# Set variable for open file name
global open_status_name
open_status_name = False
 
global selected
selected = False
 
# Create New File function
def new_file():
    # Delete previous text
    my_text.delete("1.0", END)
    root.title('New File - TextPad!')
    status_bar.config(text="New File        ")
 
    global open_status_name
    open_status_name = False
 
# Open Files
def open_file():
    my_text.delete("1.0", END)
    # Grab Filename
    text_file = filedialog.askopenfilename(initialdir= "/home/knightinmirror/Documentos", title="Open File", filetypes=(("Text Files", "*.txt"),
                                                                                                                        ("HTML Files", "*.html"),
                                                                                                                        ("Python Files", "*.py"),
                                                                                                                        ("All Files", "*.*")))
 
    # Check to see if there is a file name
    if text_file:
        # Make filename global so we can access it later
        global open_status_name
        open_status_name = text_file
 
    # Update Status bars
    name = text_file
    status_bar.config(text=f'{name}        ')
    name = name.replace("/home/knightinmirror/Documentos/", "")
    root.title(f'{name} - TextPad!')
 
    # Open the file
    text_file = open(text_file, 'r')
    stuff = text_file.read()
    # Add file to textbox
    my_text.insert(END, stuff)
    # Close the opened file
    text_file.close()
 
# Save Files
def save_file():
    global open_status_name
    if open_status_name:
        # Save the file
        text_file = open(open_status_name, "w")
        text_file.write(my_text.get(1.0, END))
        # Close the file
        text_file.close()
        status_bar.config(text=f'saved: {open_status_name}')
    else:
        save_as_file()
 
# Save As File
def save_as_file():
    text_file = filedialog.asksaveasfilename(defaultextension=" .*", initialdir='/home/knightinmirror/Documentos/',
                                             filetypes=(("Text Files", "*.txt"), ("HTML Files", "*.html"),
                                                        ("Python Files", "*.py"), ("All Files", "*.*")))
    if text_file:
        # Define name bar or status bars
        name = text_file
        status_bar.config(text=f'Saved: {name}')
        name = name.replace("/home/knightinmirror/Documentos/", "")
        root.title(f'{name} - TextPad!')
 
        # Save the file
        text_file = open(text_file, "w")
        text_file.write(my_text.get(1.0, END))
        # Close the file
        text_file.close()
 
# Cut text
def cut_text(e):
    global selected
    # Check to see if keyboard shortcut used
    if e:
        selected = root.clipboard_get()
    else:
        if  my_text.selection_get():
            # Grab selected text from text box
            selected = my_text.selection_get()
            # Delete Selected Text from text box
            my_text.delete("sel.first", "sel.last")
            # Clear the clipboard the append
            root.clipboard_clear()
            root.clipboard_append(selected)
 
# Copy text
def copy_text(e):
    global selected
    # Check to see if we used keyboard shortcut
    if e:
        selected = root.clipboard_get()
 
    if my_text.selection_get():
        # Grab selected text from text box
        selected = my_text.selection_get()
        root.clipboard_clear()
        root.clipboard_append(selected)
 
# Paste Text
def paste_text(e):
    global selected
    # Check to see if keyboard shutcut used
    if e:
        selected = root.clipboard_get()
    else:
        if selected:
            position = my_text.index(INSERT)
            my_text.insert(position, selected)
 
# Bold Text
def bold_it():
    # Create our font
    bold_font = font.Font(my_text, my_text.cget("font"))
    bold_font.configure(weight="bold")
 
    # Configure a tag
    my_text.tag_configure("bold", font=bold_font)
 
    # Define Current tags
    current_tags = my_text.tag_names("sel.first")
 
    # If statment to see if tag has been set
    if "bold" in current_tags:
        my_text.tag_remove("bold", "sel.first", "sel.last")
    else:
       my_text.tag_add("bold", "sel.first", "sel.last")
 
# Italics Text
def italics_it():
     # Create our italics
    italics_font = font.Font(my_text, my_text.cget("font"))
    italics_font.configure(slant="italic")
 
    # Configure a tag
    my_text.tag_configure("italic", font=italics_font)
 
    # Define Current tags
    current_tags = my_text.tag_names("sel.first")
 
    # If statment to see if tag has been set
    if "italic" in current_tags:
        my_text.tag_remove("italic", "sel.first", "sel.last")
    else:
       my_text.tag_add("italic", "sel.first", "sel.last")
 
# Change Selected Text Color
def  text_color():
    # Pick a color
    my_color = colorchooser.askcolor()[1]
 
    if my_color:
        # Create our font
        color_font = font.Font(my_text, my_text.cget("font"))
 
        # Configure a tag
        my_text.tag_configure("colored", font='color_font', foreground=my_color)
 
        # Define Current tags
        current_tags = my_text.tag_names("sel.first")
 
        # If statment to see if tag has been set
        if "colored" in current_tags:
            my_text.tag_remove("colored", "sel.first", "sel.last")
        else:
            my_text.tag_add("colored", "sel.first", "sel.last")
 
# Create tables
def table_it():
    pass
 
# Change bg color
def bg_color():
    my_color = colorchooser.askcolor()[1]
    if my_color:
        my_text.config(bg=my_color)
 
# Change ALL Text Color
def all_text_color():
    my_color = colorchooser.askcolor()[1]
    if my_color:
        my_text.config(fg=my_color)
 
# Highlight the selected text
def highlight_it():
    my_text.tag_add("start", "1.11","1.17")
    my_text.tag_config("start", background= "yellow", foreground= "white")
    pass
 
# Print File Function
def print_file():
    pass
 
# Select all Text
def select_all(e):
    # Add sel tag to select all text
    my_text.tag_add('sel', '1.0', 'end')
 
# Clear  all Text
def clear_all():
    my_text.delete(1.0, END)
 
# Create a toolbar frame
toolbar_frame = Frame(root)
toolbar_frame.pack(fill=X)
toolbar_frame.config(background='white', padx=60)
 
# Create Main Frame
my_frame = Frame(root)
my_frame.pack(pady=5)
 
# Create our Scrollbar for the Text Box
text_scroll = Scrollbar(my_frame)
text_scroll.pack(side=RIGHT, fill=Y)
 
# Crear un widget Text
my_text = Text(root)
 
# Configurar el widget Text
my_text.config(width=99, height=48, font=("Helvetica", 10), fg="snow",
               selectforeground="white", undo=True, bg="#000000")
 
# Background image
img = tkinter.PhotoImage(file="fondo-neon-min2.png")
 
# Agregar la imagen de fondo al widget
my_text.image_create(index="1.0", image=img)
 
my_text.pack()
 
# Configure our Scrollbar
text_scroll.config(command=my_text.yview, background='brown')
 
# Create Menu
my_menu = Menu(root)
root.config(menu=my_menu, background='brown')
 
# Add File Menu
my_menu.configure(background='brown', fg='white')
file_menu = Menu(my_menu, tearoff=False)
my_menu.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="New", command=new_file)
file_menu.add_command(label="Open", command=open_file)
file_menu.add_command(label="Save", command=save_file)
file_menu.add_command(label="Save As", command=save_as_file)
file_menu.add_separator()
file_menu.add_command(label="Print", command=print_file)
 
file_menu.add_command(label="Exit", command=root.quit)
 
# Add Edit Menu
 
edit_menu = Menu(my_menu, tearoff=False)
my_menu.add_cascade(label="Edit", menu=edit_menu)
edit_menu.add_command(label="Cut", command=lambda: cut_text(False), accelerator="\t Ctrl+x")
edit_menu.add_command(label="Copy", command=lambda: copy_text(False), accelerator="\t Ctrl+c")
edit_menu.add_command(label="Paste", command=lambda: paste_text(False), accelerator="\t Ctrl+v")
edit_menu.add_separator()
edit_menu.add_command(label="Undo", command=my_text.edit_undo, accelerator="\t Ctrl+z")
edit_menu.add_command(label="Redo", command=my_text.edit_redo, accelerator="\t Ctrl+Shift+z")
edit_menu.add_separator()
edit_menu.add_command(label="Select All", command=lambda: select_all(True), accelerator="\t Ctrl+E")
edit_menu.add_command(label="Clear", command=clear_all, accelerator="\t Ctrl+y")
 
# Add Color Menu
color_menu = Menu(my_menu, tearoff=False)
my_menu.add_cascade(label="Colores", menu=color_menu)
color_menu.add_command(label="Selected Text", command=text_color)
color_menu.add_command(label="ALL Text", command=all_text_color)
color_menu.add_command(label="Background", command=bg_color)
 
# Add status Bar to Botton of App
status_bar =Label(root, text='Ready        ', anchor=E)
status_bar.pack(fill=X, side=BOTTOM, ipady=5)
 
# Edit Bindings
root.bind('<Control-Key-x>', cut_text)
root.bind('<Control-Key-c>', copy_text)
root.bind('<Control-Key-v>', paste_text)
# Select Binding
root.bind('Control-E', select_all)
root.bind('Control-e', select_all)
 
fee = "Now what? "
my_label = Label(root, text=fee[: -1], fg='white').pack()
 
# Create Button
 
# Bold Button
bold_button = Button(toolbar_frame, text="Bold", command=bold_it, background='brown', fg='white')
bold_button.grid(row=0, column=0, sticky=W)
 
# Italics Button
italics_button = Button(toolbar_frame, text="Italics", command=italics_it, background='brown', fg='white')
italics_button.grid(row=0, column=1)
 
# Undo/Redo Buttons
undo_button = Button(toolbar_frame, text="Undo", command=my_text.edit_undo, background='brown', fg='white')
undo_button.grid(row=0, column=2)
redo_button = Button(toolbar_frame, text="Redo", command=my_text.edit_redo, background='brown', fg='white')
redo_button.grid(row=0, column=3)
 
 
# Text Color
color_text_button = Button(toolbar_frame, text="Text Color", command=text_color, background='brown', fg='white')
color_text_button.grid(row=0, column=4, padx=5)
 
# Highlight Button
highlight_button = Button(toolbar_frame, text="Highlight", command=highlight_it, background='brown', fg='white')
highlight_button.grid(row=0, column=5)
 
# Tables Button
table_button = Button(toolbar_frame, text="Tables", command=table_it, background='brown', fg='white')
table_button.grid(row=0, column=6)
 
 
root.mainloop()

¡Gracias de nuevo!
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar