如何在列表框py3中设置默认光标选择

时间:2018-06-23 08:35:51

标签: python-3.x tkinter

这是我的代码,可以正常工作当程序启动时,列表框中没有选择,并且我想在列表框中设置默认选择(对于用户未选择的情况)。任何帮助,请!

### frame_3 widgets.
frame_3 = Frame(frame_2)
label_1a = Label(frame_3, relief = 'solid', width = 17)
label_1a.configure(text = "Start of Period month")
### listbow_1 and static attributes.
listbox_1 = Listbox(frame_3, exportselection=0, width = 12, height = 12)
for item in ['January','Febuary','March',
             'April','May','June',
             'July','August','September',
             'October','November','December']:
    listbox_1.insert(END,item)

label_2a = Label(frame_3, relief = 'groove', width = 10)
label_2a.configure(text = "Start day")
entry_1 = Entry(frame_3, width = 2)
### geometry frame_3
label_1a.grid (column = 0, row = 2)
frame_3.grid  (column = 0, row = 2)
listbox_1.grid(column = 0, row = 3)
label_2a.grid (column = 0, row = 5)
entry_1.grid  (column = 1, row = 5)

1 个答案:

答案 0 :(得分:0)

您可以使用listbox.selection_set(0)选择列表中的第一项

更多文档:Listbox.selection_set

完整示例

import tkinter as tk

def test():
    # here you can get selected element
    print('previous:', listbox.get('active'))
    print(' current:', listbox.get(listbox.curselection()))

# --- main ---

root = tk.Tk()

listbox = tk.Listbox(root)
listbox.pack()

listbox.insert(1, 'Hello 1')
listbox.insert(2, 'Hello 2')
listbox.insert(3, 'Hello 3')
listbox.insert(4, 'Hello 4')
listbox.selection_set(0)

button = tk.Button(root, text="Test", command=test)
button.pack()