且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

tkinter 列表框 get(ACTIVE) 方法

更新时间:2022-12-27 18:54:51

一个项目在您点击后变为活动状态——这意味着在您的 ListboxSelect 方法返回之后.因此,您将打印出此次点击之前 处于活动状态的任何内容(通常意味着您上次点击的内容).

An item becomes active after you click on it—which means after your ListboxSelect method returns. So, you're printing out whatever was active before this click (meaning, generally, what you clicked last time).

另外,鉴于您多次提到selected",我认为您想要的是 selected 值,而不是 active 值,所以您应该问那个.

Also, given that you refer to "selected" numerous times, I think what you want is the selected value(s), not the active one, so you should be asking for that.

对于带有 selectmode=SINGLEBROWSE(默认值,您拥有的)列表框的列表框,您可以轻松修复这两个问题.只需更改此:

For a listbox with selectmode=SINGLE or BROWSE (the default, what you have) listbox, you can fix both of these trivially. Just change this:

mylistbox.get(ACTIVE)

到:

mylistbox.get(mylistbox.curselection())

如果您需要处理 MULTIPLEEXTENDED,那么当然有 0 到 7 个选项而不是 1 个,因此您需要执行以下操作:

If you need to handle MULTIPLE or EXTENDED, then of course there are anywhere from 0 to 7 selections instead of exactly 1, so you need to do something like:

values = [mylistbox.get(idx) for idx in mylistbox.curselection()]
print ', '.join(values)

虽然我们在做,但我不确定你为什么要这样做 str((mylistbox.get(ACTIVE))),甚至 str(mylistbox.get(ACTIVE))).带有单个索引的 mylistbox.get 的结果将是一个字符串,与您插入的相同.

While we're at it, I'm not sure why you were doing str((mylistbox.get(ACTIVE))), or even str(mylistbox.get(ACTIVE)). The result of mylistbox.get with a single index is going to be a string, the same one you inserted.