简体   繁体   中英

Trouble with ttk.Entry.selection_present() and ttk.Entry.selection_clear() in tkinter 8.5 and python 3.3

I need entry to contain only one file selection at a time. As it stands now, if the user hits button multiple times to select multiple files (say they selected the wrong file at first or they changed their mind), entry concatenates these multiple filenames all together. Basically, I want entry to contain only the user's last file selection.

Example Code:

from tkinter import *
from tkinter import ttk
from tkinter import filedialog

def browse():
    if entry.selection_present() == 1:
        entry.selection_clear()
    entry.insert(0, filedialog.askopenfilename(parent=frame))

root = Tk()

frame = ttk.Frame(root)
frame.pack()
entry = ttk.Entry(frame, width=100)
entry.pack()
button = ttk.Button(frame, text="Browse", command=browse)
button.pack()

root.mainloop()

Neither entry.selection_present() nor entry.selection_clear() do what I expect. entry.selection_present() always outputs 0, and entry.selection_clear() seems to do nothing.

I was able to get my code to work if I changed the if block to:

if entry.get() != "":
    entry.delete(0,1000)

but this seems kind of hackish because the arguments - delete all characters up to 1000 - is arbitrary. What I really want is to clear the entire previous file selection.

Tkinter 8.5 documentation: https://www.tcl.tk/man/tcl8.5/TkCmd/ttk_entry.htm#M23

Use END (or 'end') to denote the end of the entry.

entry.delete(0, END)

Above statement will delete entry content. (from begining(0) to the end).


Alternatively, you can bind the entry with StringVar object, and later call set('') to clear the content.

v = StringVar()
entry = Entry(master, textvariable=v)

# to clear
v.set('')

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