如何讓.selection_set()選擇欄設定為串列框中選定的隨機專案?使用.curselection()[0]僅回傳串列框中當前所選專案的索引,但是當我放置一個鏈接到串列框的隨機專案的按鈕時,選擇欄不會根據所選專案設定。我想要實作的是類似下一個按鈕,.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()
您可以看到,當按下隨機播放按鈕時,按下下一個按鈕不會將選擇欄設定為串列中選定的隨機播放專案。
uj5u.com熱心網友回復:
您需要獲取隨機索引,而不是打亂串列,因為打亂整個串列可能不是您想要的。
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/425262.html
標籤:python-3.x tkinter 按钮 洗牌
