I have following python code in Tkinter.
import tkinter as tk
window = tk.Tk()
window.geometry('200x200')
label_var = tk.StringVar()
l = tk.Label(window, bg='yellow', width=4, textvariable=label_var)
l.pack()
I want to move item of listbox when I click Next item button, but the item sill stop at item 1 No moving (move to item2)
def move():
value = lb.get(lb.curselection())
label_var.set(value)
# move items of listbox 1, 2, 3, 4
index = lb.curselection()[0]
lb.select_set(index + 1) # move to item2 but default still stop at items 1
var = tk.StringVar()
var.set((1,2,3,4))
lb = tk.Listbox(window, listvariable=var)
lb.pack()
b1 = tk.Button(window, text='Next item', command=move)
b1.pack()
window.mainloop()
How to solve it.
This what your method should look like -
def move():
value = lb.get(lb.curselection())
x1 = lb.curselection()[0]
lb.selection_clear(x1)
if x1+1==lb.size():
lb.selection_set(0)
else:
lb.selection_set(x1+1)
label_var.set(value)
Please note that, you need to handle corner cases, ie end of the list. In this code, at the end of the list, I restart at beginning.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.