[英]Tkinter Listbox How to tell if an item is selected
我正在嘗試創建一個簡單的GUI,該GUI允許用戶按下按鈕,這將從顯示的列表框中刪除條目。 但是,如果未選擇任何條目,則控制台將引發錯誤,因此我將如何確定用戶是否選擇了條目。 這是我的代碼:
selection = self.recipe_list.curselection()
if not selection is None:
self.recipe_list.delete(selection)
else:
print("Nothing to delete!")
而不是像您要檢查的那樣返回None
,它返回一個空字符串""
。 檢查如下:
if selection:
self.recipe_list.delete(selection)
else:
print("Nothing to delete!")
if not self.lstb.curselection() is ():
根據與
Tkinter參考:Python的GUI
列表框對象上的方法包括:
.curselection()
返回一個元組,其中包含所選元素的行號,從0開始計數。
如果未選擇任何內容,則返回一個空的元組。
所以你可以做這樣的事情
if self.MyListbox.curselection():
index = self.MyListbox.curselection()[0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.