Home > Software engineering >  Why label with image and Entry widget can't be together ?? Can't solve this
Why label with image and Entry widget can't be together ?? Can't solve this

Time:05-02

Hy guys please help me i have this simple code just for learn,i can see both the image "etichetta_sfondo" for the background and i can see even the entry widget, but how to put the entry widget in the middle of the image, how tu put it a bit down in the middle of the image and not just over it?

from tkinter import *
from ctypes import windll
windll.shcore.SetProcessDpiAwareness(1)
window = Tk()
window.title("Gestione spese")
window.state("zoomed")
window.geometry("1500x770")
window.call('wm', 'iconphoto', window._w, PhotoImage(file="trasparente.png"))
testo_nuova_spesa = Entry(window,borderwidth=5,font=("Ink Free",20),width=9,bg="#f2f2f2")
testo_nuova_spesa.pack()
sfondo = PhotoImage(file="soldi.png")
etichetta_sfondo = Label(window,image=sfondo)
etichetta_sfondo.pack()
window.mainloop()

enter image description here

CodePudding user response:

The simplest is to use place with relative position (in percents) and anchor in center of Entry

entry.place(relx=0.5, rely=0.5, anchor='center')

and this put Entry in center of window

And this looks like in center of image because image is also in center of window.

import tkinter as tk   # PEP8: `import *` is not preferred

window = tk.Tk()

img = tk.PhotoImage(file="lenna.png")

label = tk.Label(window, image=img)
label.pack()

entry = tk.Entry(window, bg="white")
entry.place(relx=0.5, rely=0.5, anchor='center')

window.mainloop()

enter image description here


If image is not in center then you can use Label as parent/master of Entry and place will place in center of Label.

This example puts Entry in center of second Label.

import tkinter as tk   # PEP8: `import *` is not preferred

window = tk.Tk()

img = tk.PhotoImage(file="lenna.png")

label1 = tk.Label(window, image=img)
label1.pack()

label2 = tk.Label(window, image=img)
label2.pack()

entry = tk.Entry(label2, bg="white")
entry.place(relx=0.5, rely=0.5, anchor='center')

window.mainloop()

enter image description here


Image Lenna from Wikipedia.

PEP 8 -- Style Guide for Python Code

  • Related