Home > Back-end >  Centering components in Tkinter Grid Layout not working
Centering components in Tkinter Grid Layout not working

Time:10-20

I want the components in this window to be center aligned, but no matter how I try I am unable to bring those components to the center.

Here is my code and the attached screenshot of the window when I run the code.

import tkinter.filedialog
import tkinter as tk
from PIL import ImageTk,Image
import numpy as np
import os
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mp
import tensorflow as tf


def upload():
    global img1
    global img2
    #file_types=[('JPG Files','*.jpg')]
    files=tkinter.filedialog.askopenfilenames(parent=win,title='Choose JPG Files')
    if(len(files)==0):
        return
    #-----------------------------------------------Logic For Getting Results From the Model-------------------------------------------------------
    TEST_XX=np.zeros((36,503,666,2))
    a=mp.imread(files[0])
    a=cv2.cvtColor(a,cv2.COLOR_BGR2GRAY)
    b=mp.imread(files[1])
    b=cv2.cvtColor(b,cv2.COLOR_BGR2GRAY)
    TEST_XX[0,:,:,0] = b
    TEST_XX[0,:,:,1] = a
    img1=ImageTk.PhotoImage(Image.open(files[1]))
    img2=ImageTk.PhotoImage(Image.open(files[0]))
    tk.Label(win,image=img1,width=250,height=250).grid(row=2,column=0)
    tk.Label(win,image=img2,width=250,height=250).grid(row=2,column=1)
    print(files)
    test=TEST_XX[0,:,:,:]
    test=np.reshape(test,[1,503,666,2])
    expected=new_model.predict([test])
    tk.Label(win,text='Estimated Soil Moisture Content is: {}'.format(expected[0][0]),font=('times',16,'bold')).grid(row=3,column=0,columnspan=2)

new_model = tf.keras.models.load_model("C:\\Users\\srira\\Dropbox\\My PC (DESKTOP-7I4SSBF)\\Desktop\\SEM-VII\\MINI-PROJECT\\dataset\\smc_model_v5")
win=tk.Tk()
win.title("SMC Estimator")
win.geometry("600x600")
font=('times',20,'bold')
l=tk.Label(win, text='SMC Estimation Using Regression-CNN',font=font)
l.grid(row=0,column=0,columnspan=2)
b=tk.Button(win,text='Upload',font=font,command=lambda: upload())
b.grid(row=1,column=0,columnspan=2)

win.mainloop()

Output Image When I run the above code

CodePudding user response:

Have you tried setting 'sticky' to expand horizontally, e.g.

grid(row=0, column=0, columnspan=2, sticky='ew')

you could also try adding weight=1 like so

win.grid_columnconfigure(0, weight=1)  # '0' refers to column 0
  • Related