I have trouble placing my text where I want. In the following code, my image is placed in the middle of the screen, which is what I want, but my text is at the very botton of the screen, but I want them to be together at the middle.
from tkinter import *
fenetre = Tk()
width = 350
height = 299
image = PhotoImage(file="carre.png")
canvas = Canvas(fenetre, width=width, height=height, bd=0, highlightthickness=0)
canvas.create_image(width/2, height/2, image=image, anchor=CENTER)
canvas.pack(expand=YES)
entree = Entry(fenetre, font=("sans-serif",20))
entree.pack()
bouton = Button(fenetre, text="CALCULER", font=("sans-serif",20), fg = "black") # fg = foreground
bouton.pack()
bouton.bind("<Button-1>")
fenetre.mainloop()
CodePudding user response:
The problem is that you have used expand=YES
for the canvas. That means that all extra space in the window will be allocated to the canvas, even if the canvas doesn't use it. This causes any widgets packed below the canvas to be pushed all of the way to the bottom of the window.
It's hard to say what the right solution is, since it's unclear what other widgets might be in the same window, and what behavior you want when the window is resized.
The simplest solution is to remove expand=YES
. That will cause pack
to use as little space as necessary for the canvas. Then, when you pack the entry and text they will be right up against the bottom of the canvas. All extra space will be allocated below the button.
Another solution would be to put the canvas, entry, and widget in a frame rather than directly in the root. Then, you can use pack
, place
, or grid
to center that frame in the window.