9
votes

When i create button + entry + button in grid, entry was centered but not completely fill the column. How i can fill the column via Entry?

enter image description here

# Python 3.4.1

import io
import requests
import tkinter as tk
from PIL import Image, ImageTk

def get_image():
    im = requests.get('http://lorempixel.com/' + str(random.randint(300, 400)) + '/' + str(random.randint(70, 120)) + '/')
    return Image.open(io.BytesIO(im.content))


class ImageSelect(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)

        master.resizable(width=False, height=False)
        master.title('Image manager')
        master.iconify = False
        master.deiconify = False
        master.grab_set = True

        image = ImageTk.PhotoImage(get_image())
        self.image = tk.Label(image=image)
        self.image.image = image
        self.image.grid(row=0, columnspan=3)


        self.reload = tk.Button(text='Reload').grid(row=1, column=0, sticky='w')
        self.path = tk.Entry().grid(row=1, column=1, sticky='we')
        self.submit = tk.Button(text='Submit').grid(row=1, column=2, sticky='e')

root = tk.Tk()
app = ImageSelect(master=root)
app.mainloop()
2

2 Answers

24
votes

Using grid() you can use grid_columnconfigure() on parent of Entry

import tkinter as tk

root = tk.Tk()

tk.Entry(root).grid(sticky='we')
root.grid_columnconfigure(0, weight=1)

root.mainloop()

Using pack() you could use fill='x'

import tkinter as tk

root = tk.Tk()

tk.Entry(root).pack(fill='x')

root.mainloop()

BTW: using:

self.path = tk.Entry().grid()

you assign result of grid() to self.path but grid() always return None.

If you need self.path then do:

self.path = tk.Entry()
self.path.grid()

If you don't need self.path then you could do:

tk.Entry().path.grid()
2
votes

An Entry widget's width is defined by the width property. It is measured in # of characters. As far as I know there is no native way to make the Entry automatically resize to fit a space. You can set the width like this (the default is 20):

self.path = tk.Entry(width=28).grid(row=1, column=1, sticky='we')

If you really want the Entry to automatically grow or shrink, you could bind an event to the window resizing that recalculates and and resets the necessary width of the Entry, but it'll be kinda ugly.