Skip to content

Instantly share code, notes, and snippets.

@ajfigueroa
Last active July 4, 2017 22:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajfigueroa/11034002 to your computer and use it in GitHub Desktop.
Save ajfigueroa/11034002 to your computer and use it in GitHub Desktop.
A subclass of Tkinters Entry class that allows for dynamic sizing. Assign a delegate, ensure callback is implemented and set offset to desired value to extend to (such as 2 * text length)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import Tkinter as Tk
class ResizeableEntry(Tk.Entry):
"""
Class that adds resizing functionality to the Tkinter Entry class.
Makes callbacks to the delegate on whether it should resize and how much it should.
"""
def __init__(self, parent=None, delegate=None, **options):
Tk.Entry.__init__(self, parent, **options)
self.delegate = delegate
def pack(self, **options):
"""
Override packing function to acquire all the pack options.
"""
Tk.Entry.pack(self, **options)
if not hasattr(self, 'defaultPackOptions'):
# Only set default pack options once
self.defaultPackOptions = options
def resize(self, offset=0):
try:
# Ask the delegate if it should resize the entry
if self.delegate.should_resize():
# Resize the default pack options if there
# is an offset and subtract after applying offset
# to avoid overgrowing
self.defaultPackOptions['ipadx'] += offset
self.pack(**self.defaultPackOptions)
self.defaultPackOptions['ipadx'] -= offset
except AttributeError:
print "No delegate exists for ResizeableEntry object %d." % id(self)
@mi-lee
Copy link

mi-lee commented Jul 4, 2017

Bless

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment