4
1

More than 3 years have passed since last update.

[python] tkinter コンボボックスの値を連動させる

Posted at

記事の内容

pythonでtkinterを使ったGUIアプリを製作中、comboboxの扱いで少し悩んだのでメモ。
コンボボックスA,Bを2つ作成し、Combobox-Aの値に連動してCombobox-Bの値が変わるようにしたかった。

例えばCombobox-Aには県名、Combobox-Bには市名を選択する際に
Combobox-Aで県名を選択 -> その県に含まれる市名をCombobox-Bで選択可能にする、といった具合。

用意するもの

  • 県名をキー、市名のリストを値にもつ辞書
  • tkinter

実装

import tkinter as tk
import tkinter.ttk as ttk

dict = ['県名1':[市名1, 市名2, ... ], '県名2':[市名1, 市名2, ... ], ...]
  :
  :
root = tk.Tk()
var_material = tk.StringVar()
combo_A = ttk.Combobox(root, values=list(dict.keys()) , textvariable=var_material)
combo_A.bind('<<ComboboxSelected>>', lambda event: combo_B.config(values=dict[var_material.get()]))

combo_B = ttk.Combobox(root, values=list(dict[var_material.get()]))

var_material = tk.StringVar()
combo_A = ttk.Combobox(root, values=list(dict.keys()) , textvariable=var_material)

combo_Aで選択できる値には、辞書のキーを設定する。
また、変化する値としてtextvariableにvar_material(=tk.StringVar())を設定。


combo_A.bind('<<ComboboxSelected>>', lambda event: combo_B.config(values=dict[var_material.get()]))

combo_Aで選択された際のイベントとして、combo_Bの値を、辞書の市名リストに変更するようにバインド。


combo_B = ttk.Combobox(root, values=list(dict[var_material.get()]))

combo_Bで選択できる値に、辞書からキーに対応するリストとする。

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1