如何根据 tkinter 列表框中随机项目的索引设置选择栏

How to set the selection bar based on the index of the shuffled items in the tkinter listbox

如何让 .selection_set() 将选择栏设置为列表框中选定的随机项目?仅使用 .curselection()[0] returns 列表框中当前所选项目的索引,但是当我放置一个链接到列表框随机项目的按钮时,选择栏未根据所选项目设置物品。我想要实现的是类似于下一步按钮,.curselection()[0] + 1。但是我不需要在列表中向下移动,而是需要它根据选定的随机项目进行移动,例如 .curselection()[0] + "the index of the selected shuffled item"。下面是我要解释的可运行代码:

import tkinter as tk
from random import shuffle

root = tk.Tk()
root.geometry('300x200')
root.resizable(False, False)
root.title('Listbox')

is_shuffling = False
item_index = 0

langs = ['Java', 'C#', 'C', 'C++', 'Python',
        'Go', 'JavaScript', 'PHP', 'Swift']

langs_var = tk.StringVar(value=langs)

listbox = tk.Listbox(root, listvariable=langs_var, height=6)

listbox.grid(column=0, row=0, sticky='nwes')

bottom_frame = tk.Frame()
bottom_frame.grid(row=1, column=0, sticky="ew")
bottom_frame.grid_columnconfigure(2, weight=1)
bottom_frame.grid_rowconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)


shuffle(langs)

def go_next():
    global is_shuffling
    global langs
    shuffle(langs)
    if is_shuffling:
        item_index = listbox.curselection()[0]
        listbox.selection_clear(0, tk.END)
        listbox.selection_set(item_index)
        listbox.activate(item_index)
        print(langs)
    else:
        try:
            idx = listbox.curselection()[0] + 1
            listbox.selection_clear(0, tk.END)
            listbox.selection_set(idx)
            listbox.activate(idx)
        except IndexError:
            listbox.selection_set(0)
            listbox.activate(0)

def toggle_shuffle():
    global is_shuffling
    if is_shuffling:
        shuffle_btn.config(text="Shuffle Off")
        is_shuffling = False
    else:
        shuffle_btn.config(text="Shuffle On")
        is_shuffling = True

shuffle_btn = tk.Button(bottom_frame, relief=tk.SUNKEN, text="Shuffle", bg="silver", highlightthickness=0, bd=0, command=toggle_shuffle)
shuffle_btn.grid(row=1, column=0)

next_btn = tk.Button(bottom_frame, relief=tk.SUNKEN, text="Next Button", bg="silver", highlightthickness=0, bd=0, command=go_next)
next_btn.grid(row=1, column=1, padx=10)

print(langs)

root.mainloop()

您可以看到,当按下随机播放按钮时,按下一个按钮不会将选择栏设置为从列表中选择的已随机播放的项目。

您需要获取随机索引,而不是打乱列表,因为打乱整个列表可能不是您想要的。

from random import randint

def go_next():
    if is_shuffling:
        rand = randint(0,listbox.size()-1) # Get random index within range
        listbox.selection_clear(0, tk.END)
        listbox.selection_set(rand) # Set the index
        listbox.activate(rand)
    else:
        try:
            idx = listbox.curselection()[0] + 1
            listbox.selection_clear(0, tk.END)
            listbox.selection_set(idx)
            listbox.activate(idx)
        except IndexError:
            listbox.selection_set(0)
            listbox.activate(0)