简体   繁体   中英

Check if Python (3.4) Tkinter Entry is Full

I am using a standard tkinter entry to input a directory path. When the user presses enter - if the physical length of the string exceeds that of the entry, I want the program to modify the displayed text to ...[end of directory]. I have the logistics of this figured out but as of yet I have no accurate way to test whether the entry box is full, or how full

Things I have tried:

  • Using 'PIL.ImageFont.truetype("font.otp",fontsize).size' - cannot calculate the point at which to cut the directory
  • Simply using the length of the string against the length of the entry- inaccurate as the font I am using (which I don't want to change if possible) varies in length with each character

Another compromise behaviour which I tried was to make the entry "look" at the start of the path. I tried inserting at, selecting at and moving the cursor to position 0 but none of these worked

You can use xview method of Entry . xview return the visible part of the text displayed in the entry. You can use it to interactively create a text that fit the entry.

Here is a quick and dirty proof of concept

from tkinter import *

root = Tk()

v = StringVar(root)
e = Entry(root,textvariable=v)
e.pack(fill=BOTH)
v.set('abcdefghijklmnopqrstuvwxyz0123456789')

new_s = None

def check_length():
    global new_s
    original_s = v.get()

    def shorten():
        global new_s
        e.xview(0)
        if e.xview()[1] != 1.0:
            new_s = new_s[:-4] + '...'
            v.set(new_s)
            print("new_s: " + new_s)
            e.xview(0)
            e.after(0,shorten)
            print(e.xview()[1])
    if e.xview() != (0.0,1.0):
        new_s = original_s + '...'
        shorten()

b = Button(root,text="hop",command=check_length)
b.pack()

e.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM