リストボックスを使う

リストボックスを使ってみます。

 

import tkinter as tk
from tkinter import StringVar

### メインウィンドウ ###
root = tk.Tk()
root.geometry("+{}+{}".format(200, 200))
frame = tk.Frame(root, width=300, height=300, bg="white")
frame.pack(padx=10, pady=10)

### Listbox ###
var = StringVar(value=["BTC", "BCH", "LSK"])
listbox = tk.Listbox(frame,
                     listvariable=var,
                     height=4)
listbox.pack()

### Button ###
button = tk.Button(root, text="button", command=None)
button.pack(pady=10)


root.mainloop()

このプログラムを実行すると、下のウィンドウが立ち上がります。

f:id:pytry3g:20180702160121p:plain

このままでは、リストボックス内のアイテムを選択しても何も起こらないので、プログラムを少しいじります。

選択したアイテムを取得する

選択したアイテムを取得できるように、2つの方法を紹介します。

どちらも、手順は同じです。

Listboxのメソッドのcurselectionで選択されているアイテムのインデックスを取得します。これはタプルで返されます。

次にgetメソッドにインデックスを渡して、選択されたアイテムのテキストを取得します。

ボタンを利用する方法

commandの部分をNoneからbutton_selectedに変更し、下の関数を追加します。

ボタンをクリックしたら、選択されているアイテムをテキストで出力するようになります。

def button_selected():
    if len(listbox.curselection()) == 0:
        return
    index = listbox.curselection()[0]
    print(listbox.get(index))

button = tk.Button(root, text="button", command=button_selected)

バインディングを利用する方法

バインディングを利用すると、アイテムが選択されたとき、選択されているアイテムをテキストで出力します。

def bind_selected(event):
    if len(listbox.curselection()) == 0:
        return
    index = listbox.curselection()[0]
    print(listbox.get(index))

root.bind("<<ListboxSelect>>", bind_selected)