如果在未選擇條目的情況下執行 ListboxSelect 回呼,即在相應串列框中的單擊已放置在空白空間中最后一項的下方,則“curselection”方法始終回傳串列框中最后一項的索引。更重要的是,如果嘗試對串列框使用默認的“瀏覽”選擇方法,并在按住滑鼠按鈕的同時將滑鼠游標移動到串列框上,則任何移動都會執行回呼。我試圖找到有關如何修復它的提示......但沒有運氣。
from tkinter import *
class simple( Frame ):
def __init__( self, parent = None ):
Frame.__init__( self )
self.master.title( 'DEMO' )
self.master.bind( '<Control-q>', quit )
self.pack()
self.create_widgets()
def create_widgets( self ):
words = ['An','"empty"','selection','processes','the', 'last', 'item','in','this','list' ]
self.lb = Listbox ( self, width = 12, height = 25, selectmode = SINGLE, exportselection = False )
self.lb.pack ( side = LEFT )
self.lb.bind ( '<<ListboxSelect>>', self.process_item )
Label ( self, anchor = W, text = '\n\nClick here\n\n<--\n\nin the emtpy space...' ).pack ( side = RIGHT )
for w in words:
self.lb.insert ( 0, w )
def process_item ( self, event ):
selection = self.lb.curselection ( )
self.do_stuff_with_item ( self.lb.get ( selection ) )
self.lb.delete ( selection )
def do_stuff_with_item ( self, item ):
print ( item )
def engage():
root = Tk()
sw = simple( root )
sw.pack()
root.mainloop()
if __name__ == '__main__':
engage()
我用 python 2.7、3.6(在 Linux 上)和 python 3.8 在 Win 上嘗試過
uj5u.com熱心網友回復:
實作你所要求的確實很棘手。
的默認行為Listbox是在獲得焦點時選擇最后一個專案。
為了愚弄它,您可以添加一個空詞作為您words串列的最后一項。這將使其在Listbox. 然后在您的process_item回呼中,檢查所選值是否為空(如果它也是最后一個值,也可以選擇)。Listbox如果是這樣,請從您的回呼中洗掉焦點并回傳。這看起來好像什么都沒發生。
這是修改后的代碼:
from tkinter import *
class simple(Frame):
def __init__(self, parent=None):
Frame.__init__(self)
self.master.title('DEMO')
self.master.bind('<Control-q>', quit)
self.pack()
self.create_widgets()
def create_widgets(self):
# Words with dummy "" word in the end
words = ['An', '"empty"', 'selection', 'processes', 'the', 'last', 'item', 'in', 'this', 'list', ""]
self.lb = Listbox(self, width=12, height=25, selectmode=SINGLE, exportselection=False)
self.lb.pack(side=LEFT)
self.lb.bind('<<ListboxSelect>>', self.process_item)
Label(self, anchor=W, text='\n\nClick here\n\n<--\n\nin the emtpy space...').pack(side=RIGHT)
self.lb.insert(0, *words)
def process_item(self, event):
selection = self.lb.curselection()
item = self.lb.get(selection)
if item == "":
# It's last dummy item, remove focus and return
self.master.after(0, self.master.focus)
return
# Real item was clicked
self.do_stuff_with_item(item)
self.lb.delete(selection)
def do_stuff_with_item(self, item):
print(item)
def engage():
root = Tk()
sw = simple(root)
sw.pack()
root.mainloop()
if __name__ == '__main__':
engage()
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/446468.html
上一篇:插入和當前有什么區別?
