简体   繁体   English

在tkinter 8.5和python 3.3中遇到ttk.Entry.selection_present()和ttk.Entry.selection_clear()的问题

[英]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. 我需要entry一次仅包含一个文件选择。 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. 现在,如果用户多次单击button以选择多个文件(例如,他们最初选择了错误的文件或改变了主意),则entry将这些多个文件名连接在一起。 Basically, I want entry to contain only the user's last file selection. 基本上,我希望entry仅包含用户的最后文件选择。

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()entry.selection_clear()都没有entry.selection_clear()我的期望。 entry.selection_present() always outputs 0, and entry.selection_clear() seems to do nothing. entry.selection_present()始终输出0, entry.selection_clear()似乎什么也不做。

I was able to get my code to work if I changed the if block to: 如果将if块更改为:我可以使我的代码工作:

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

but this seems kind of hackish because the arguments - delete all characters up to 1000 - is arbitrary. 但这似乎有点骇人听闻,因为参数-删除最多1000个字符-是任意的。 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 Tkinter 8.5文档: https : //www.tcl.tk/man/tcl8.5/TkCmd/ttk_entry.htm#M23

Use END (or 'end') to denote the end of the entry. 使用END (或'end')表示条目的结尾。

entry.delete(0, END)

Above statement will delete entry content. 以上声明将删除条目内容。 (from begining(0) to the end). (从开始(0)到结束)。


Alternatively, you can bind the entry with StringVar object, and later call set('') to clear the content. 另外,您可以将条目与StringVar对象绑定,然后再调用set('')清除内容。

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

# to clear
v.set('')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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