Search code examples
pythonvalidationtkinterwidthtkinter-entry

Python Tkinter Entry how to get width of the entry


vcmd = (self.register(self.validate_entry_len), '%P', '%W')

ip_entry = tk.Entry(ip_frame, width=15, validate='key', vcmd=vcmd)
port_entry = tk.Entry(port_frame, width=5, validate='key', vcmd=vcmd)

def validate_entry_len(self, P, W):
    entry = self.master.nametowidget(W)
    if len(P) <= !!!width of entry!!!:
        return True

    self.bell()
    return False

So I am trying to validate the text inside the entry whether it exceeds the max length or not. I have two entry widgets with different length. I want to use the same validation function with different lengths for each so that I don't need to make two validation function when the only difference is the max length. Therefore, I am trying to use the width of the widget. However, I can't find a way to get the width.


Solution

  • You can access the character width of the Entry widget with entry['width']. Keep in mind that this may not be reliably updated if the widget is modified.